并查集

https://leetcode.cn/problems/number-of-islands/

给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。

岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。

此外,你可以假设该网格的四条边均被水包围。

 

 

 

public class Daoyuone {
    static int fa[], rank[];
    static int cnt;

    public static int find(int x) {
        return fa[x] = fa[x] == x ? x : find(fa[x]);
    }

    public static void union(int x, int y) {
        int xx = find(x);
        int yy = find(y);
        if (xx != yy) {
            if (rank[xx] > rank[yy])
                fa[yy] = xx;
            else if (rank[yy] > rank[xx])
                fa[xx] = yy;
            else {
                fa[xx] = yy;
                rank[yy] += 1;
            }
            cnt--;
        }
    }

    static int dir[][] = { { 0, 1 }, { 0, -1 }, { -1, 0 }, { 1, 0 } };

    public static int numIslands(char[][] grid) {

        int n = grid.length;
        int m = grid[0].length;
        fa = new int[m * n + 1];
        rank = new int[m * n + 1];
        for (int i = 0; i < m * n; i++)
            fa[i] = i;
        cnt = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {

                if (grid[i][j] == '1') {

                    cnt++;
                    for (int k = 0; k < 4; k++) {
                        int ii = i + dir[k][0];
                        int jj = j + dir[k][1];
                        if (ii >= 0 && ii < n && jj >= 0 && jj < m && grid[ii][jj] == '1') {
                            union(i * n + j, ii * n + jj);
                        }
                    }
                }
            }

        }
        return cnt;

    }

    public static void main(String[] args) {
        String s[] = { "11000", "11000", "00100", "00011" };
        int sn = s.length;
        int sm = s[0].length();
        char c[][] = new char[sn][sm];
        for (int i = 0; i < sn; i++) {
            for (int j = 0; j < sm; j++) {
                c[i][j] = s[i].charAt(j);
            }
        }

        System.out.println(numIslands(c));
    }
}

 

posted on 2022-08-31 10:13  cltt  阅读(19)  评论(0编辑  收藏  举报

导航