题目
给你一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
思路
利用dfs遍历当前节点相邻的岛屿。
class Solution:def numIslands(self, grid: List[List[str]]) -> int:if not grid or len(grid) == 0: return 0rows, cols = len(grid), len(grid[0])count = 0for row in range(rows):for col in range(cols):if grid[row][col] == '1':count += 1 # 进行了多少次深度优先搜索,就有多少个岛屿self.dfs(grid, row, col)return countdef dfs(self, grid, row, col):if row < 0 or row >= len(grid) or col < 0 or col >= len(grid[0]) or grid[row][col] != '1':returnelse:grid[row][col] = '2'# 探索上下左右四个方向self.dfs(grid, row - 1, col) # 上self.dfs(grid, row + 1, col) # 下self.dfs(grid, row, col - 1) # 左self.dfs(grid, row, col + 1) # 右
二刷代码
class Solution:def numIslands(self, grid: List[List[str]]) -> int:rows, cols = len(grid), len(grid[0])if rows == 0 or cols == 0: return 0visited = grid[:][:] # 用于标记访问过的位置count = 0 # 岛屿数量for row in range(rows):for col in range(cols):if grid[row][col] == '1' and visited[row][col] != -1:self.dfs(row, col, visited, rows, cols, grid)count += 1print(visited)return countdef dfs(self, row, col, visited, rows, cols, grid):if row < 0 or row >= rows or col < 0 or col >= cols or grid[row][col] == '0' or visited[row][col] == -1:returnvisited[row][col] = -1# 上下左右self.dfs(row - 1, col, visited, rows, cols, grid)self.dfs(row + 1, col, visited, rows, cols, grid)self.dfs(row, col - 1, visited, rows, cols, grid)self.dfs(row, col + 1, visited, rows, cols, grid)
