首页 > 代码库 > [LeetCode] 547. Friend Circles

[LeetCode] 547. Friend Circles

https://leetcode.com/problems/friend-circles

public class Solution {
    int[] id;
    int[] weight;
    public int findCircleNum(int[][] M) {
        if (M == null || M.length == 0 || M[0].length == 0) {
            return 0;
        }
        initUnionFind(M.length);
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < M.length; i++) {
            for (int j = 0; j < M[0].length; j++) {
                if (i == j) {
                    continue;
                }
                if (M[i][j] == 1) {
                    union(i, j);
                }
            }
        }
        for (int i = 0; i < id.length; i++) {
            int root = find(i);
            if (!set.contains(root)) {
                set.add(root);
            }
        }
        return set.size();
    }
    
    private void initUnionFind(int n) {
        id = new int[n];
        weight = new int[n];
        for (int i = 0; i < n; i++) {
            id[i] = i;
            weight[i] = 1;
        }
    }
    private void union(int i, int j) {
        int rootI = find(i);
        int rootJ = find(j);
        if (rootI == rootJ) {
            return;
        }
        if (weight[rootI] > weight[rootJ]) {
            id[rootJ] = rootI;
            weight[rootI] += weight[rootJ];
        } else {
            id[rootI] = rootJ;
            weight[rootJ] += weight[rootI];
        }
    }
    private int find(int i) {
        while (i != id[i]) {
            return find(id[i]);
        }
        return i;
    }
}

 

[LeetCode] 547. Friend Circles