Skip to content

Commit

Permalink
Merge f5557d6 into 2e2d8b2
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Nov 13, 2018
2 parents 2e2d8b2 + f5557d6 commit f7d986c
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,4 @@ problems from
* [Day 81](https://github.com/vaskoz/dailycodingproblem-go/issues/171)
* [Day 82](https://github.com/vaskoz/dailycodingproblem-go/issues/173)
* [Day 83](https://github.com/vaskoz/dailycodingproblem-go/issues/175)
* [Day 84](https://github.com/vaskoz/dailycodingproblem-go/issues/177)
42 changes: 42 additions & 0 deletions day84/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package day84

// CountIslands returns the number of islands.
// 1 represents land, and 0 represents water.
// Runs in O(GridSize) and uses O(GridSize) space.
func CountIslands(grid [][]int) int {
visited := make([][]bool, len(grid))
for i := range visited {
visited[i] = make([]bool, len(grid[i]))
}
islands := 0
for i := range grid {
for j := range grid[i] {
if grid[i][j] == 1 && !visited[i][j] {
islands++
exploreIsland(grid, visited, i, j)
}
}
}
return islands
}

// exploreIsland is a DFS of the island
func exploreIsland(grid [][]int, visited [][]bool, i, j int) {
visited[i][j] = true
if up := i - 1; up >= 0 && isUnexplored(grid[up][j], visited[up][j]) {
exploreIsland(grid, visited, up, j)
}
if down := i + 1; down < len(grid) && isUnexplored(grid[down][j], visited[down][j]) {
exploreIsland(grid, visited, down, j)
}
if left := j - 1; left >= 0 && isUnexplored(grid[i][left], visited[i][left]) {
exploreIsland(grid, visited, i, left)
}
if right := j + 1; right < len(grid[i]) && isUnexplored(grid[i][right], visited[i][right]) {
exploreIsland(grid, visited, i, right)
}
}

func isUnexplored(gridValue int, visitedStatus bool) bool {
return gridValue == 1 && !visitedStatus
}
34 changes: 34 additions & 0 deletions day84/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package day84

import "testing"

var testcases = []struct {
grid [][]int
expected int
}{
{[][]int{
{1, 0, 0, 0, 0},
{0, 0, 1, 1, 0},
{0, 1, 1, 0, 0},
{0, 0, 0, 0, 0},
{1, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
}, 4},
}

func TestCountIslands(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := CountIslands(tc.grid); result != tc.expected {
t.Errorf("Expected %v got %v", tc.expected, result)
}
}
}

func BenchmarkCountIslands(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
CountIslands(tc.grid)
}
}
}

0 comments on commit f7d986c

Please sign in to comment.