Number of Islands
https://leetcode.com/problems/number-of-islands/
Solution 1: DFS
if not grid:
return 0
m, n = len(grid), len(grid[0])
def dfs(row, col) -> None:
nonlocal grid, m, n
if not (
0 <= row < m and
0 <= col < n and
grid[row][col] == '1'
):
return
grid[row][col] = '0'
dfs(row - 1, col)
dfs(row + 1, col)
dfs(row, col - 1)
dfs(row, col + 1)
num_islands = 0
for row in range(m):
for col in range(n):
if grid[row][col] == "1":
dfs(row, col)
num_islands += 1
return num_islandsSolution 2: BFS
def bfs(row, col) -> None:
nonlocal grid, m, n
if not (
0 <= row < m and
0 <= col < n and
grid[row][col] == '1'
):
return
grid[row][col] = '0'
dfs(row - 1, col)
dfs(row + 1, col)
dfs(row, col - 1)
dfs(row, col + 1)