给你一个由 '1'
(陆地)和 '0'
(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1
输入: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'
代码如下:
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
row = len(grid)
col = len(grid[0])
used = [[-1 for i in range(col)] for j in range(row)]
result = 0
def findIsland(i,j):
if used[i][j] == -1 and grid[i][j] == "1":
used[i][j] = 1
# 上
if i-1 >= 0 and grid[i-1][j] == "1":
findIsland(i-1,j)
# 左
if j-1 >= 0 and grid[i][j-1] == "1":
findIsland(i, j-1)
# 右
if j+1 < col and grid[i][j+1] == "1":
findIsland(i,j+1)
# 下
if i+1 < row and grid[i+1][j] == "1":
findIsland(i+1,j)
for i in range(row):
for j in range(col):
if used[i][j] == 1 or grid[i][j] == "0":
continue
else: # grid[i][j] == "1" and used[i][j] == -1
result = result + 1
findIsland(i,j)
#result
print("============")
print(result)
return result
本题解题思路为找出所有相连的岛屿,这里单独使用方法findIsland
去遍历当前所有相邻的岛屿,使用used
二维数组去存储已经遍历过的岛屿,在寻找当前岛屿所有的相邻岛屿时,需要考虑上下左右四个方向,每找到一个新的岛屿都会在used
数组中进行标记,并且继续判断上下左右四个方向是否还有新的相邻岛屿,其本质是深度遍历。