LeetCode 1254. Number of Closed Islands解题报告(python)

1254. Number of Closed Islands

  1. Number of Closed Islands python solution

题目描述

Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.
Return the number of closed islands.
在这里插入图片描述
在这里插入图片描述

解析

使用深度优先遍历,对逐个连通的小岛进行遍历,每次遍历后将小岛的值更改为-1,为防止重复遍历。
分别从四个角开始,对整个珊格的小岛进行遍历。
然后统计走不到的小岛的个数(即0的个数),这些小岛就属于被孤立的小岛。

                if grid[i][j]==0:
                    dfs(i,j,-1)
                    res+=1

但是针对example1的情况,出现大量互相连通孤立小岛,在找到其中一个小岛后,需要在对小岛进行连通遍历,避免重复计数。上述代码

class Solution:
    def closedIsland(self, grid: List[List[int]]) -> int:
        if not grid:
            return 0
        m,n=len(grid),len(grid[0])     
        
        def dfs(i,j,val):
            if(0<=i<m and 0<=j<n and grid[i][j]==0):
                grid[i][j]=val
                dfs(i+1,j,-1)
                dfs(i-1,j,-1)
                dfs(i,j+1,-1)
                dfs(i,j-1,-1)
        
        for i in range(m):
            for j in range(n):
                if(i==0 or i==m-1 or j==0 or j==n-1) and grid[i][j]==0:
                    dfs(i,j,-1)
        
        res=0
        for i in range(m):
            for j in range(n):
                if grid[i][j]==0:
                    dfs(i,j,-1)
                    res+=1
        
        return res

Reference

https://leetcode.com/problems/number-of-closed-islands/discuss/425122/Python-easy-understand-DFS-solution
https://blog.csdn.net/fuxuemingzhu/article/details/81126995

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值