题目链接: https://leetcode-cn.com/problems/number-of-islands/
给你一个由 '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'
'1'
时,执行深搜,深搜的关键是将这个'1'
初始化掉(我这里采用的是变为'*'
),然后继续对下一个相邻的'1'
执行同样的操作,这样,同一块符合相邻条件的岛屿就会被灭掉。然后跳出分支。岛屿数量+=1
[x-1][y]
、[x+1][y]
、[x][y-1]
、[x][y+1]
x==0
或者x==len(grid)-1
判断上下边界,使用y==0
或者y==len(grid[0])-1
防止数组越界。grid
列表一定要作为全局变量使用class Solution:
def numIslands(self, grid: list[list[str]]) -> int:
def dfs(x, y):
grid[x][y] = '*' # 炸平该点,将当前节点变为一个非'1'的其他字符
for i in [-1, 1]: # 取x的两个位置
if (i == -1 and x != 0) or (i == 1 and x != len(grid) - 1): # 判断数组越界
if grid[x + i][y] == '1': # 如果此点也是岛屿,那么对其进行炸平,继续搜索与之相邻的点
dfs(x + i, y)
for j in [-1, 1]: # 取y的两个位置
if (j == -1 and y != 0) or (j == 1 and y != len(grid[0]) - 1): # 判断数组越界
if grid[x][y + j] == '1': # 如果此点也是岛屿,那么对其进行炸平,继续搜索与之相邻的点
dfs(x, y + j)
c = 0 # 初始化岛屿数量
for i in range(len(grid)): # 开始对列表进行遍历
for j in range(len(grid[0])):
if grid[i][j] == '1': # 如果该点是一个岛屿,那么进行深搜
c += 1
dfs(i, j)
return c