题解 | #岛屿数量#
岛屿数量
https://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e
class Solution: def solve(self, grid): if not grid: return 0 rows = len(grid) cols = len(grid[0]) count = 0 def dfs(row, col): if ( row < 0 or row >= rows or col < 0 or col >= cols or grid[row][col] != "1" ): return grid[row][col] = "#" # 标记当前陆地已经访问过,避免重复计数 # 递归地探索相邻的陆地 dfs(row - 1, col) # 上 dfs(row + 1, col) # 下 dfs(row, col - 1) # 左 dfs(row, col + 1) # 右 # 遍历整个矩阵 for row in range(rows): for col in range(cols): if grid[row][col] == "1": count += 1 # 发现一个新的岛屿 dfs(row, col) # 使用DFS遍历该岛屿的所有陆地 return count