200. 岛屿数量 https://leetcode-cn.com/problems/number-of-islands/
func numIslands(grid [][]byte) int { n := len(grid) if n == 0{ return 0 } //初始全部未访问过 false。注意二: 给的是一个n*m数组,而不是n*n数组 flag := make([][]bool,n) m := len(grid[0]) for i:=0;i<n;i++{ flag[i] = make([]bool,m) } res := 0 for i:=0;i<n;i++{ for j:=0;j<m;j++{ if flag[i][j] == false && grid[i][j] == '1'{ dfs(flag,grid,n,m,i,j) res++ } } } return res } //注意一 不是else逻辑。 func dfs(flag [][]bool,grid [][]byte, n,m ,i,j int) { if flag[i][j] == false && grid[i][j] == '1'{ flag[i][j] = true if i-1 >=0{ dfs(flag,grid,n,m,i-1,j) } if i+1 <n{ dfs(flag,grid,n,m,i+1,j) } if j-1>=0{ dfs(flag,grid,n,m,i,j-1) } if j+1<m{ dfs(flag,grid,n,m,i,j+1) } } return }
优化不需要额外的flag数组,直接将元数组的1改成0
func numIslands(grid [][]byte) int { n := len(grid) if n == 0{ return 0 } m := len(grid[0]) res := 0 for i:=0;i<n;i++{ for j:=0;j<m;j++{ if grid[i][j] == '1'{ dfs(grid,n,m,i,j) res++ } } } return res } //注意一 不是else逻辑。 func dfs(grid [][]byte, n,m ,i,j int) { if grid[i][j] == '1'{ grid[i][j] = '0' if i-1 >=0{ dfs(grid,n,m,i-1,j) } if i+1 <n{ dfs(grid,n,m,i+1,j) } if j-1>=0{ dfs(grid,n,m,i,j-1) } if j+1<m{ dfs(grid,n,m,i,j+1) } } return }
继续使用广度优先遍历,广度优先法稍微麻烦些,广度优先需要借助队列
func numIslands(grid [][]byte) int { n := len(grid) if n == 0{ return 0 } m := len(grid[0]) res := 0 for i:=0;i<n;i++{ for j:=0;j<m;j++{ if grid[i][j] == '1'{ bfs(grid,pair{i,j},n,m) res++ } } } return res } type pair struct { x int y int } //注意一 不是else逻辑。 func bfs(grid [][]byte,p pair, n,m int) { if grid[p.x][p.y] == '1'{ grid[p.x][p.y] = '0' var queue []pair if p.x-1 >=0{ queue = append(queue,pair{p.x-1,p.y}) } if p.x+1 < n{ queue = append(queue,pair{p.x+1 ,p.y}) } if p.y-1>=0{ queue = append(queue,pair{p.x,p.y-1}) } if p.y+1<m{ queue = append(queue,pair{p.x,p.y+1}) } for len(queue) !=0 { bfs(grid,queue[0],n,m) queue = queue[1:] } } return }
优化下广度优先遍历
func numIslands(grid [][]byte) int { n := len(grid) if n == 0{ return 0 } m := len(grid[0]) res := 0 for i:=0;i<n;i++{ for j:=0;j<m;j++{ if grid[i][j] == '1'{ res++ var queue []pair queue = append(queue,pair{i,j}) for len(queue) !=0 { p := queue[0] queue = queue[1:] if p.x-1 >=0 && grid[p.x-1][p.y] == '1'{ queue = append(queue,pair{p.x-1,p.y}) grid[p.x-1][p.y] = '0' } if p.x+1 < n && grid[p.x+1][p.y] == '1'{ queue = append(queue,pair{p.x+1,p.y}) grid[p.x+1][p.y] = '0' } if p.y-1 >=0 && grid[p.x][p.y-1] == '1'{ queue = append(queue,pair{p.x,p.y-1}) grid[p.x][p.y-1] = '0' } if p.y+1 < m && grid[p.x][p.y+1] == '1'{ queue = append(queue,pair{p.x,p.y+1}) grid[p.x][p.y+1] = '0' } } } } } return res } type pair struct { x int y int }