200.岛屿数量
200.岛屿数量
题解
思路:上下左右是1的就是同一块地方,问一个二维矩阵有多少个地方,dfs,遇到1变成0即可
代码
package main func numIslands(grid [][]byte) int { cnt := 0 for i := 0; i < len(grid); i++ { for j := 0; j < len(grid[i]); j++ { if grid[i][j] == '1' { dfs(grid, i, j) cnt++ } } } return cnt } func dfs(grid [][]byte, i, j int) { if i < 0 || i >= len(grid) || j < 0 || j >= len(grid[0]) { return } if grid[i][j] == '1' { grid[i][j] = '0' dfs(grid, i-1, j) dfs(grid, i+1, j) dfs(grid, i, j-1) dfs(grid, i, j+1) } return } func main() { }