213 - 200 岛屿数量
题目
解答
深度优先
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
directions = [(-1, 0), (0, -1), (1, 0), (0, 1)]
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
marked = [[False for _ in range(n)] for _ in range(m)]
count = 0
def dfs(i, j):
marked[i][j] = True
for direction in directions:
new_i = i + direction[0]
new_j = j + direction[1]
if 0 <= new_i and new_i < m and 0 <= new_j and new_j < n and \
not marked[new_i][new_j] and grid[new_i][new_j] == "1":
dfs(new_i, new_j)
for i in range(m):
for j in range(n):
if not marked[i][j] and grid[i][j] == "1":
count += 1
dfs(i, j)
return count广度优先
dfs之挖人工湖
光头大佬的版本

Last updated