[leetcode] 1020. Number of Enclaves

Description

Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)

A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid.

Return the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number of moves.

Example 1:

Input: [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3
Explanation: 
There are three 1s that are enclosed by 0s, and one 1 that isn't enclosed because its on the boundary.

Example 2:

Input: [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
Output: 0
Explanation: 
All 1s are either on the boundary or can reach the boundary.

Note:

  1. 1 <= A.length <= 500
  2. 1 <= A[i].length <= 500
  3. 0 <= A[i][j] <= 1
  4. All rows have the same size.

分析

题目的意思是:给定一个矩阵,1代表陆地,0表示海洋;返回网格中无法在任意次数的移动中离开矩阵边界的陆地的数量。这道题一看就是一个dfs的题目,把能到达边界的陆地填上2,剩下的保持1的陆地就是离不开矩阵边界的陆地了,如果能想到这个就好办了。

  • 从边界上的1开始深度优先搜索,把遍历到的1填上2.
  • 遍历矩阵统计1的个数就是答案了。

代码

class Solution:
    def dfs(self,A,i,j):
        m=len(A)
        n=len(A[0])
        if(i<0 or i>=m or j<0 or j>=n):
            return
        
        if(A[i][j]==1):
            A[i][j]=2
            self.dfs(A,i-1,j)
            self.dfs(A,i+1,j)
            self.dfs(A,i,j-1)
            self.dfs(A,i,j+1)
        
    def numEnclaves(self, A: List[List[int]]) -> int:
        m=len(A)
        n=len(A[0])
        for i in range(m):
            for j in range(n):
                if(i==0 or i==m-1 or j==0 or j==n-1):
                    if(A[i][j]==1):
                        self.dfs(A,i,j)
        res=0             
        for i in range(m):
            for j in range(n):
                if(A[i][j]==1):
                    res+=1
        return res
        

参考文献

[LeetCode] 1020. Number of Enclaves

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

农民小飞侠

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

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

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

打赏作者

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

抵扣说明:

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

余额充值