Given a 2d grid map of '1’s (land) and '0’s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
func numIslands(grid [][]byte) int {
if len(grid) == 0 {
return 0
}
res := 0
m, n := len(grid), len(grid[0])
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
res += int(grid[i][j]) - '0'
dfs(grid, i, j, m, n)
}
}
return res
}
func dfs(graph [][]byte, i int, j int, m int, n int) {
if i < 0 || i >= m || j < 0 || j >= n || graph[i][j] == '0' {
return
}
graph[i][j] = '0'
dfs(graph, i+1, j, m, n)
dfs(graph, i-1, j, m, n)
dfs(graph, i, j+1, m, n)
dfs(graph, i, j-1, m, n)
}
本文深入探讨了计算二维网格中岛屿数量的算法。通过遍历地图并利用深度优先搜索(DFS)来标记和计数岛屿,提供了详细的代码实现及示例说明。

487

被折叠的 条评论
为什么被折叠?



