力扣热题51

200. 岛屿数量 - 力扣(LeetCode)https://leetcode.cn/problems/number-of-islands/submissions/628256822/?envType=study-plan-v2&envId=top-100-liked

深度优先递归

双层循环进行遍历,对每个1进行计数作为岛屿,然后进入递归将这个1四周的1的四周都变为0即淹没,最后得到答案

复制代码
#python
class Solution:
    def dfs(self,grid,a,b):
        grid[a][b]=0
        c,d=len(grid),len(grid[0])
        for x,y in [(a-1,b),(a+1,b),(a,b-1),(a,b+1)]:
            if 0<=x<c and 0<=y<d and grid[x][y]=="1":
                self.dfs(grid,x,y)
    def numIslands(self, grid: List[List[str]]) -> int:
        a=len(grid)
        if a==0:
            return 0
        b=len(grid[0])
        ans=0
        for i in range(a):
            for j in range(b):
                if grid[i][j]=="1":
                    ans=ans+1
                    self.dfs(grid,i,j)
        return ans
相关推荐
NAGNIP1 天前
轻松搞懂全连接神经网络结构!
人工智能·算法·面试
NAGNIP1 天前
一文搞懂激活函数!
算法·面试
董董灿是个攻城狮1 天前
AI 视觉连载7:传统 CV 之高斯滤波实战
算法
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
爱理财的程序媛1 天前
openclaw 盯盘实践
算法
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python
端平入洛1 天前
auto有时不auto
c++
JordanHaidee1 天前
Python 中 `if x:` 到底在判断什么?
后端·python