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
解法
使用DFS, 遍历grid, 如果找到小岛, 则将它所有连接的岛标记为#, 并且计数加一.
Time: O(m*n)
Space: O(1)
class Solution:
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if not grid: return 0
count = 0
r, c = len(grid), len(grid[0])
for i in range(r):
for j in range(c):
# if we meet the island, mark all the adjacent islands
if grid[i][j] == '1':
self.dfs(grid, i, j)
count += 1
return count
def dfs(self, grid, i, j):
# base case
if not (0 <= i<len(grid) and 0<= j < len(grid[0]) and grid[i][j] == '1'):
return
grid[i][j] = '#'
self.dfs(grid, i-1, j)
self.dfs(grid, i+1, j)
self.dfs(grid, i, j-1)
self.dfs(grid, i, j+1)
本文介绍了一种使用深度优先搜索(DFS)算法解决二维网格中岛屿数量统计问题的方法。通过遍历网格,标记并计数相连的陆地,实现了高效计算。详细解析了算法流程,包括边界条件判断、递归调用等关键步骤。
4842

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



