方法1:深度优先搜索
遍历网格中的所有点,如果值为1,则岛屿数量+1,进行深度优先搜索
DFS:
设置grid[r][c]=0已经访问
然后对上下左右四个方向,如果满足条件(x,y在长度范围内,并且网格值为1),继续进行DFS
class Solution:
def dfs(self, grid, r, c):
grid[r][c] = 0
nr, nc = len(grid), len(grid[0])
for x, y in [(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)]:
if 0 <= x < nr and 0 <= y < nc and grid[x][y] == "1":
self.dfs(grid, x, y)
def numIslands(self, grid: List[List[str]]) -> int:
nr = len(grid)
if nr == 0:
return 0
nc = len(grid[0])
num_islands = 0
for r in range(nr):
for c in range(nc):
if grid[r][c] == "1":
num_islands += 1
self.dfs(grid, r, c)
return num_islands
方法2:广度优先搜索
借助队列实现
遍历所有网格元素,如果网格值为1,就开始BFS。
每次BFS,就让岛屿数量加1,
让该网格值为0,表示已经访问了
把该网格值放进队列中,
循环取出队列中的值,进行四个方向的搜索,如果满足条件:就添加到队列中,并修改该网格的值为0,表示已经访问了。
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
nr = len(grid)
if nr == 0:
return 0
nc = len(grid[0])
num_islands = 0
for r in range(nr):
for c in range(nc):
if grid[r][c] == "1":
num_islands += 1
grid[r][c] = "0"
neighbors = collections.deque([(r, c)])
while neighbors:
row, col = neighbors.popleft()
for x, y in [(row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1)]:
if 0 <= x < nr and 0 <= y < nc and grid[x][y] == "1":
neighbors.append((x, y))
grid[x][y] = "0"
return num_islands
方法1:
时间复杂度:O(MN)
空间复杂度:O(MN)
方法2:
时间复杂度:O(MN)
空间复杂度:O(min(M,N))