zoukankan      html  css  js  c++  java
  • 飞地的数量

    给出一个二维数组 A,每个单元格为 0(代表海)或 1(代表陆地)。

    移动是指在陆地上从一个地方走到另一个地方(朝四个方向之一)或离开网格的边界。

    返回网格中无法在任意次数的移动中离开网格边界的陆地单元格的数量。

    示例 1:

    输入:[[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
    输出:3
    解释:
    有三个 1 被 0 包围。一个 1 没有被包围,因为它在边界上。
    示例 2:

    输入:[[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
    输出:0
    解释:
    所有 1 都在边界上或可以到达边界。
     

    提示:

    1 <= A.length <= 500
    1 <= A[i].length <= 500
    0 <= A[i][j] <= 1
    所有行的大小都相同

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/number-of-enclaves
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    class Solution {
    int dire[][]={{-1,0},{0,1},{1,0},{0,-1}};
    int row;
    int col;
    int [][] A;
    public int numEnclaves(int[][] A) {
        this.A=A;
        if(A==null || A.length==0)
            return 0;
        row=A.length;
        col=A[0].length;
        int ret=0;
        for(int i=0;i<row;i++){
            if(A[i][0]==1){
                helper(i,0);
            }
            if(A[i][col-1]==1)
            {
                helper(i,col-1);
            }
        }
        for(int i=0;i<col;i++){
            if(A[0][i]==1){
                helper(0,i);
            }
            if(A[row-1][i]==1){
                helper(row-1,i);
            }
        }
        for(int i=0;i<row;i++){
            for(int j=0;j<col;j++){
                if(A[i][j]==1)
                    ret++;
            }
        }
        return ret;
    }
    public void helper(int i,int j){
        if(i<0 || i>=row || j<0 || j>=col || A[i][j]==0)
            return;
        A[i][j]=0;
        for(int k=0;k<4;k++){
            int x=dire[k][0]+i;
            int y=dire[k][1]+j;
            helper(x,y);
        }
    }
    }
  • 相关阅读:
    Brunch with a Friend 与朋友共进午餐
    Linux使用tcpdump抓取网络数据包示例
    Linux LVM逻辑卷配置过程详解
    Linux不停往外发包
    jumpserver遇到的坑
    Python3.5 使用Sqlite3
    git rebase小计(转)
    pip3 更改安装源
    jquery ajax(3).post
    jquery ajax (2)实例 .GET
  • 原文地址:https://www.cnblogs.com/-jiuqi/p/13450850.html
Copyright © 2011-2022 走看看