java-给定一个表格,求里面有多少个块 - 草稿

image.png

上下左右相连的为一个块,如上图,共有三个块
现给定一个n*n的表格求出所有的块数,采用湮灭法,每到一个块,就把所有的子元素清零

public class FindBlocks {
    public static int find(int[][] a) {
        int result = 0;
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                if (a[i][j] != 0) {
                    dispear(a, i, j);
                    result++;
                }
            }
        }
        return result;
    }

    public static void dispear(int[][] a, int i, int j) {
        if (a[i][j] == 0) return;
        a[i][j] = 0;
        //up
        if (j - 1 >= 0&& a[i][j - 1] != 0 ) {
            dispear(a, i, j - 1);
        }

        //down
        if (j + 1 < a.length&&a[i][j + 1] != 0  ) {
            dispear(a, i, j + 1);
        }

        //left

        if (i - 1 >=0&&a[i - 1][j] != 0  ) {
            dispear(a, i - 1, j);
        }

        //right
        if (i + 1 < a.length&&a[i + 1][j] != 0  ) {
            dispear(a, i + 1, j);
        }
    }

    public static void main(String[] args){
    int[][] a={{1,1,1,0,0,0,1},{1,0,0,0,0,0,0},{1,1,0,0,0,0,0},
            {0,0,0,0,1,1,0},{0,0,1,0,0,0,1},{0,0,0,0,0,0,0}};
    int r = find(a);
    System.out.println(r);
   }
}

你可能感兴趣的:(java-给定一个表格,求里面有多少个块 - 草稿)