【问题标题】:Given 2D Matrix, Find the number of islands of connected 1s present in the matrix [duplicate]给定 2D 矩阵,找出矩阵中存在的连接 1 的岛的数量 [重复]
【发布时间】:2020-06-18 10:30:21
【问题描述】:

给定一个由 0 和 1 组成的矩阵。找出矩阵中存在的连接 1 的岛的数量。 注意:如果一个 1 周围有另一个 1(8 个方向中的任何一个),则称 1 为已连接。

我写了如下代码:

class Islands {

    // Function to find the number of island in the given list A
    // N, M: size of list row and column respectively
    static boolean isSafe(int i, int j, ArrayList<ArrayList<Boolean>> visited, int R, int C,ArrayList<ArrayList<Integer>> A){
        return ((i>=0 && i<R) && (j>=0 && j<C) && (A.get(i).get(j)==1) && (!visited.get(i).get(j)));
    }
    static void BFS(ArrayList<ArrayList<Integer>> A,ArrayList<ArrayList<Boolean>> visited,int x , int y){
        int[] x_pos = {-1,-1,-1,0,0,1,1,1};
        int[] y_pos = {-1,0,1,-1,1,-1,0,1};
        visited.get(x).add(y,true);
        for(int k=0;k<8;k++){
            if(isSafe(x+x_pos[k],y+y_pos[k],visited,A.size(),A.get(0).size(),A))
                BFS(A,visited,x+x_pos[k],y+y_pos[k]);
        }
    }
    
    static int findIslands(ArrayList<ArrayList<Integer>> A, int N, int M) {
        ArrayList<ArrayList<Boolean>> visited = new ArrayList<>();
        for(int i=0;i<N;i++) {
            visited.add(i,new ArrayList<Boolean>(M));
        }
        for(int i=0;i<N;i++){
            for(int j=0;j<M;j++){
                visited.get(i).add(j,false);
            }
        }
        int num = 0;
        for(int i=0;i<N;i++){
            for(int j=0;j<M;j++){
                if((A.get(i).get(j)==1) && (!visited.get(i).get(j))){
                    BFS(A, visited,i,j);
                    num++;
                }
            }
        }
        return num;
        
    }
}

对于测试用例

1 1 0

0 0 1

1 0 1

它返回 3 而不是 2。

在调试时,我发现访问的数组被这样修改

真真假

假假真

假假

真真假

假假真

真假

真真假

假假真

真假

我不明白的是我的代码的哪一部分将值 true 更改为 false(突出显示的)。 请提出建议。

【问题讨论】:

  • Its returning 3 instead of 2. 3 实际上是正确的。
  • 另外,您正在做的是 DFS,而不是 BFS。此外,如果您可以使用 boolean[][] 而不是 arraylist,它将更具可读性。

标签: algorithm data-structures graph depth-first-search breadth-first-search


【解决方案1】:

类数组列表

public void add(int index, E元素)

在此列表中的指定位置插入指定元素。移动当前所在的元素 位置(如果有)和右侧的任何后续元素(添加一个 到他们的索引)。

See the documentation

实际上你在最后 push 值,然后从

true true false

false false true

false false true

true true false

false false true

true false false true

【讨论】:

    猜你喜欢
    • 2018-02-06
    • 2016-03-01
    • 2012-04-10
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多