[leetcode] 1254. Number of Closed Islands

这篇博客介绍了一种解决二维网格中闭合岛屿计数的方法。通过深度优先搜索(DFS)策略,遍历0值(表示陆地)并将其标记为2,若在搜索过程中遇到边界则设置标志位为False,表示该岛屿不闭合。最后统计标记为2且边界未触碰的岛屿数量。这种方法避免了重复遍历并有效地找到了所有闭合的岛屿。
摘要由CSDN通过智能技术生成

Description

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.

Example 1:

Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
Output: 2
Explanation: 
Islands in gray are closed because they are completely surrounded by water (group of 1s).

Example 2:

Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
Output: 1

Example 3:

Input: grid = [[1,1,1,1,1,1,1],
               [1,0,0,0,0,0,1],
               [1,0,1,1,1,0,1],
               [1,0,1,0,1,0,1],
               [1,0,1,1,1,0,1],
               [1,0,0,0,0,0,1],
               [1,1,1,1,1,1,1]]
Output: 2

Constraints:

  1. 1 <= grid.length, grid[0].length <= 100
  2. 0 <= grid[i][j] <=1

分析

题目的意思是:找出矩阵中被包围的0区域的个数,我的思路很直接,把0的区域天秤2,这样的话,就避免了重复遍历;然后如果在填2的过程中走到了边界,说明它不是闭合的,即被1包围,我用flag记录一下就行了。

代码

class Solution:
    def dfs(self,grid,i,j):
        if(i<0 or i>=len(grid) or j<0 or j>=len(grid[0])):
            return 
        if(grid[i][j]==0):
            grid[i][j]=2
            if(i==len(grid)-1 or i==0 or j==0 or j==len(grid[0])-1):
                self.flag=False
        else: return 
        dirs=[(0,-1),(0,1),(-1,0),(1,0)]
        for d in dirs:
            x=i+d[0]
            y=j+d[1]
            self.dfs(grid,x,y)
    def closedIsland(self, grid: List[List[int]]) -> int:
        m=len(grid)
        n=len(grid[0])
        res=0
        for i in range(m):
            for j in range(n):
                if(grid[i][j]==0):
                    self.flag=True
                    self.dfs(grid,i,j)
                    if(self.flag):
                        res+=1
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值