zoukankan      html  css  js  c++  java
  • 【leetcode】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.

    解题思路:本题和以前的岛屿问题是一样的,用DFS/BFS就好了。

    代码如下:

    class Solution(object):
        def numEnclaves(self, A):
            """
            :type A: List[List[int]]
            :rtype: int
            """
            direction = [(1,0),(-1,0),(0,1),(0,-1)]
            count_0 = 0
            count_2 = 0
            for i in range(len(A)):
                for j in range(len(A[i])):
                    if A[i][j] == 0:
                        count_0 += 1
                        continue
                    elif (i == 0 or j == 0 or i == len(A) - 1 or j == len(A[0])-1) and A[i][j] == 1:
                        A[i][j] = 2
                        queue = [(i,j)]
                        count_2 += 1
                        while len(queue) > 0:
                            a,b = queue.pop(0)
                            for (x,y) in direction:
                                if (x + a >= 0) and (x+ a < len(A)) and (y + b >= 0) and (y+b < len(A[i])) and A[x+a][y+b] == 1:
                                    A[x + a][y + b] = 2
                                    count_2 += 1
                                    queue.append((x+a,y+b))
            #print A
            return len(A) * len(A[0]) - count_0 - count_2
  • 相关阅读:
    小程序官方请求封装
    小程序天/小时/分秒倒计时封装
    小程序不定数量左右滑动中间放大轮播图效果
    小程序换行符检测换行
    小程序点击图片重新排序写法
    基于webuploader.js的单图片上传封装
    VMware Fusion 11 序列号
    Ionic 4 beta + Capacitor beta 尝鲜
    C语言学习笔记之动态分配数组空间
    C语言学习笔记之获取文件长度
  • 原文地址:https://www.cnblogs.com/seyjs/p/10636834.html
Copyright © 2011-2022 走看看