给你一个由 '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
解题思路: 网格结构的遍历,使用DFS遍历方法,判断上下左右四个方向是否满足邻域条件,首先看是否在大的网格内即是否是有效点,然后再用深度遍历的方法递归的遍历陆地的地方,为了防止重复遍历,遍历过的陆地值置为“2”,当该陆地的位置为“1”才对该网格做递归遍历
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
self.rows = len(grid)
self.cols = len(grid[0])
def valid(r, c):
if 0 <= r < self.rows and 0 <= c < self.cols:
return True
else:
return False
def dfs(r, c):
if not valid(r, c):
return
if grid[r][c] != "1":
return
grid[r][c] = "2"
dfs(r - 1, c)
dfs(r + 1, c)
dfs(r, c - 1)
dfs(r, c + 1)
res = 0
for r in range(self.rows):
for c in range(self.cols):
if grid[r][c] == "1":
dfs(r, c)
res += 1
return res