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,累加得到最后的结果。

posted @ 2019-07-17 18:55  bossman  阅读(219)  评论(0编辑  收藏  举报