目录
题目
- 给你一个由 '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
- 遍历图中所有的位置,如果该位置为1,则向外扩展将与之相连的1全部变为0
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
m = len(grid)#行数
n = len(grid[0])#列数
res = 0
def dfs(x, y):
if grid[x][y] == '1':#本身改为0
grid[x][y] = '0'
else:
return
#相连的1都改为0
if x > 0:#左边递归
dfs(x - 1, y)
if x < m - 1:#右边递归
dfs(x + 1, y)
if y > 0:#上边递归
dfs(x, y - 1)
if y < n - 1:#下边递归
dfs(x, y + 1)
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
dfs(i, j)
res += 1#岛屿数加1
return res
标签:200,递归,res,岛屿,网格,dfs,grid,数量
From: https://www.cnblogs.com/lushuang55/p/18095318