岛屿数量文章来源:https://www.toymoban.com/news/detail-698731.html
又被称为 FloodFill 算法文章来源地址https://www.toymoban.com/news/detail-698731.html
class NumIslands:
"""
floodFill 算法
https://leetcode.cn/problems/number-of-islands/
"""
def solution(self, grid: List[List[str]]) -> int:
res = 0
m, n = len(grid), len(grid[0])
for i in range(m):
for j in range(n):
if grid[i][j] == '1':
res += 1
self.dfs_matrix(grid, i, j)
return res
def dfs_matrix(self, grid, i, j):
m, n = len(grid), len(grid[0])
# 跳出递归条件
if i < 0 or i >= m or j < 0 or j >= n:
return
if grid[i][j] == '0':
return
grid[i][j] = '0'
self.dfs_matrix(grid, i - 1, j) # 上
self.dfs_matrix(grid, i + 1, j) # 下
self.dfs_matrix(grid, i, j - 1) # 左
self.dfs_matrix(grid, i, j + 1) # 右
到了这里,关于岛屿数量 -- 二维矩阵的dfs算法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!