美文网首页leetcode刷题总结 python版
leetcode 1020. Number of Enclave

leetcode 1020. Number of Enclave

作者: PJCK | 来源:发表于2019-07-11 21:56 被阅读0次

    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 <= A.length <= 500
    • 1 <= A[i].length <= 500
    • 0 <= A[i][j] <= 1
    • All rows have the same size.

    注意:
    • 边界上没有飞地,哪怕是1,也不是飞地。
    • 和边界上的1连接的地,也不是飞地。

    所以,面对这个情况,我的思路是BFS,可以先在边界上遍历,面对有1,把这个1变为除0和1以外的其他数字a,然后依次遍历,把与a连接的地(是1)变为a。最后再次遍历,统计1的个数。

    python3代码:

    class Solution:
        def numEnclaves(self, A: List[List[int]]) -> int:
            m, n = len(A), len(A[0])
            q = []
            dx = [1, -1, 0, 0]
            dy = [0, 0, 1, -1]
            for i in range(m):
                if A[i][0] == 1:
                    A[i][0] = 2
                if A[i][n-1] == 1:
                    A[i][n-1] = 2
            for i in range(n):
                if A[0][i] == 1:
                    A[0][i] = 2
                if A[m-1][i] == 1:
                    A[m-1][i] = 2
            for i in range(m):
                for j in range(n):
                    if A[i][j] == 2: # 这个必须为2.。。。。。。
                        q.append((i, j))
                        while len(q):
                            Q = q.pop(0)
                            r, c = Q[0], Q[1]
                            for k in range(4):
                                x = r + dx[k]
                                y = c + dy[k]
                                if 0 <= x < m and 0 <= y < n and A[x][y] == 1:
                                    A[x][y] = 2
                                    q.append((x, y))
            num = 0
            for i in range(m):
                for j in range(n):
                    if A[i][j] == 1:
                        num += 1
            return num
    

    注意别把q.append()弄成q.push(),不能把python和C++弄混,emmmmm。

    相关文章

      网友评论

        本文标题:leetcode 1020. Number of Enclave

        本文链接:https://www.haomeiwen.com/subject/fzmjkctx.html