[LeetCode] 547. Friend Circles

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-547.Friend Circles

LeetCode 547. Friend Circles 20170626 补上周

[LeetCode] 547. Friend Circles 朋友圈

(BFS 持续更新) leetcode 547. Friend Circles

547. Friend Circles

Leetcode之深度优先搜索(DFS)专题-547. 朋友圈(Friend Circles)