给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:
输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1
示例 2:
输入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
输出:3
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] 的值为 '0' 或 '1'
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-islands
解题思路:
思路一:判断有几个岛屿的关键是看有哪些1是被0所包围的,那么我们可以遍历grid对每一个为1的位置进行DFS,并将已经遍历过的位置标记为True然后记录下DFS的次数就是岛屿的数量;AC代码如下:
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
length = len(grid)
width = len(grid[0])
# 生成对应的二维数组
maps = [[False] * width for i in range(length)]
ans = 0
def DFS(i, j):
maps[i][j] = True
if i - 1 >= 0 and grid[i - 1][j] == "1" and not maps[i - 1][j]:
DFS(i - 1, j)
if i + 1 < length and grid[i + 1][j] == "1" and not maps[i + 1][j]:
DFS(i + 1, j)
if j - 1 >= 0 and grid[i][j - 1] == "1" and not maps[i][j - 1]:
DFS(i, j - 1)
if j + 1 < width and grid[i][j + 1] == "1" and not maps[i][j + 1]:
DFS(i, j + 1)
for i in range(length):
for j in range(width):
if grid[i][j] == "1" and not maps[i][j]:
DFS(i, j)
ans += 1
return ans
思路二:我们还可以使用BFS,通过collections中的deque将每个grid中为1的位置加入到队列中然后进行搜索,AC代码如下:
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
length = len(grid)
width = len(grid[0])
ans = 0
queue = collections.deque()
for i in range(length):
for j in range(width):
if grid[i][j] == "1":
queue.append((i, j))
ans += 1
grid[i][j] = "0"
while queue:
index_i, index_j = queue.popleft()
for x, y in [(index_i - 1, index_j), (index_i + 1, index_j), (index_i, index_j - 1),
(index_i, index_j + 1)]:
if 0 <= x < length and 0 <= y < width and grid[x][y] == "1":
queue.append((x, y))
grid[x][y] = "0"
return ans