200. Number of Islands
深度優先搜索
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
rows = len(grid)
cols = len(grid[0])
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
def dfs(row, col):
grid[row][col] = '#'
for dr, dc in directions:
next_row = row+dr
next_col = col+dc
if 0 <= next_row < rows and 0 <= next_col < cols and grid[next_row][next_col] == '1':
dfs(next_row, next_col)
islands = 0
for row in range(rows):
for col in range(cols):
if grid[row][col] == '1':
islands += 1
dfs(row, col)
return islands 廣度優先搜索
Last updated