赞
踩
1、通过递归的方式实现岛屿数量的计算
(1)寻找某一个 1 为入口,迭代将与它相连的 1 都标记为0,这样直到相连的一整块周围都没有 1 ,只有0的时候,迭代结束
(2)完成(1)中的 一个完整的迭代一次,就代表找到了一块岛屿
(3)在整个网格上循环找为 1 的入口,然后计算岛屿的数量
- class Solution:
- def numIslands(self, grid):
- def mark_zeros(grid, i, j, num_row, num_column):
- grid[i][j] = "0"
- for x, y in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:
- if 0 <= x < num_row and 0 <= y < num_column and grid[x][y] == "1":
- mark_zeros(grid, x, y, num_row, num_column)
-
- num_row = len(grid)
- if num_row == 0:
- return 0
-
- num_column = len(grid[0])
-
- # 定义岛屿的数量
- num_island = 0
-
- # 循环找岛屿数
- for i in range(num_row):
- for j in range(num_column):
- if grid[i][j] == "1":
- num_island += 1
-
- # 将与该“1”相连的所有“1”标记为“0”,直到无法标记
- mark_zeros(grid, i, j, num_row, num_column)
-
- return num_island
2、通过 bfs 的方式实现岛屿数量的查询,跟递归方式的思想和流程一样,只是将每次相连的 "1" 通过迭代的方式标记,变为 将相连的节点加入队列,直到当前队列满员,并且都标记为“0”为止。
- class Solution:
- def numIslands(self, grid):
- import collections
- num_row = len(grid)
- if num_row == 0:
- return 0
-
- num_column = len(grid[0])
-
- # 定义岛屿的数量
- num_island = 0
-
- # 循环找岛屿数
- for i in range(num_row):
- for j in range(num_column):
- if grid[i][j] == "1":
- num_island += 1
- grid[i][j] = "0"
-
- # 将与该“1”相连的所有“1”标记为“0”,直到无法标记
- queue = collections.deque([(i, j)])
- while queue:
- current_x, current_y = queue.popleft()
- for x, y in [(current_x - 1, current_y), (current_x + 1, current_y), (current_x, current_y - 1),
- (current_x, current_y + 1)]:
- if 0 <= x < num_row and 0 <= y < num_column and grid[x][y] == "1":
- queue.append((x, y))
- grid[x][y] = "0"
-
- return num_island
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。