-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumber-of-islands.go
52 lines (44 loc) · 1002 Bytes
/
number-of-islands.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package main
import "fmt"
// source: https://leetcode.com/problems/number-of-islands/
func numIslands(grid [][]byte) int {
var res int
var extractIsland func(i, j int)
extractIsland = func(i, j int) {
if i < 0 || i >= len(grid) || j < 0 || j >= len(grid[0]) || grid[i][j] != '1' {
return
}
grid[i][j] = '2'
extractIsland(i-1, j)
extractIsland(i+1, j)
extractIsland(i, j-1)
extractIsland(i, j+1)
}
for i := range grid {
for j := range grid[i] {
if grid[i][j] == '1' {
res++
extractIsland(i, j)
}
}
}
return res
}
func main() {
// Example 1
var grid1 = [][]byte{
{'1', '1', '1', '1', '0'},
{'1', '1', '0', '1', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '0', '0', '0'},
}
fmt.Println("Expected: 1 Output: ", numIslands(grid1))
// Example 2
var grid2 = [][]byte{
{'1', '1', '0', '0', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '1', '0', '0'},
{'0', '0', '0', '1', '1'},
}
fmt.Println("Expected: 3 Output: ", numIslands(grid2))
}