LeetCode in Python 1020. Number of Enclaves

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.

Solution:

class Solution(object):
    def numEnclaves(self, A):
        """
        :type A: List[List[int]]
        :rtype: int
        """
        rows, cols = len(A), len(A[0])

        def dfs(x, y):
            if x < 0 or x == rows or y < 0 or y == cols:
                return False, 0
            if A[x][y] == 0:
                return True, 0
                
            A[x][y] = 0

            l, ln = dfs(x-1, y)
            r, rn = dfs(x+1, y)
            u, un = dfs(x, y-1)
            d, dn = dfs(x, y+1)
            if l and r and u and d:
                return True, 1+ln+rn+un+dn
            else:
                return False, 0 

        res = 0
        for i in range(rows):
            for j in range(cols):
                if A[i][j] == 0: continue 
                valid, num = dfs(i, j)
                if valid:
                    res += num
        return res

注意每次dfs递归必须向四个方向遍历,不可以单独判断某个方向的结果,因为每次递归都将1置为0,只向一个方向调用dfs就返回可能会造成有错误的结果。这题和经典的Number of islands很像,只不过递归结束的条件稍有不同。如果到了grid的边缘,说明会walk off the grid,所以这个方向的dfs不符合要求,所有可以连通的1都属于无效的land,需要置为0。

在二维grid上进行for循环,需要先判断是否为1,再遍历调用dfs,累加得到最后的结果。

转载于:https://www.cnblogs.com/lowkeysingsing/p/11203008.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值