leetcode 200. 岛屿的个数

题解

遍历grid,遇到数值为1时置为0,然后不断递归上下左右的位置为0

示例代码(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
func numIslands(grid [][]byte) int {
m := len(grid)
if m == 0 {
return 0
}
n, res := len(grid[0]), 0
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == '1' {
res++
dfs(grid, i, j, m, n)
}
}
}
return res
}

func dfs(grid [][]byte, i, j, m, n int) {
grid[i][j] = '0'
if i-1 >= 0 && grid[i-1][j] == '1' {
dfs(grid, i-1, j, m, n)
}
if j-1 >= 0 && grid[i][j-1] == '1' {
dfs(grid, i, j-1, m, n)
}
if i+1 < m && grid[i+1][j] == '1' {
dfs(grid, i+1, j, m, n)
}
if j+1 < n && grid[i][j+1] == '1' {
dfs(grid, i, j+1, m, n)
}
}