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