547.省份数量并查集

class Solution {

    int[] pre;

    public int findCircleNum(int[][] isConnected) {
        int n = isConnected.length;
        pre = new int[n];
        for (int i = 0; i < n; i++) {
            pre[i] = i;
        }
        for (int i = 0; i < isConnected.length; i++) {
            for (int j = 0; j < isConnected[i].length; j++) {
                if (isConnected[i][j] == 1) {
                    int x = find(i);
                    int y = find(j);
                    if (x != y) {
                        pre[x] = y;
                    }
                }
            }
        }
        int cnt = 0;
        boolean[] flag = new boolean[n];
        for (int i = 0; i < flag.length; i++) {
            flag[i] = false;
        }
        for (int i = 0; i < n; i++) {
            if (flag[find(i)] == false) {
                cnt++;
                flag[find(i)] = true;
            }
        }
        return cnt;
    }

    //查找祖先
    int find(int x) {
        if (pre[x] == x) {
            return x;
        } else {
            int root = find(pre[x]);
            pre[x] = root;
            return pre[x];
        }
    }
}

 

posted @ 2021-01-18 14:46  缘未到  阅读(70)  评论(0编辑  收藏  举报