使用并查集计算朋友圈的个数

题目

假设一个班级中有n个学生。学生之间有些是朋友,有些不是。朋友关系是可以传递的。例如,假如AB是朋友,BC是朋友,则AC是间接朋友。定义朋友圈就是一组直接朋友或间接朋友的学生。输入一个n x n的矩阵M表示班级的朋友关系,如果M[i][j] = 1,那么学生ij是直接朋友。请计算该班级中朋友圈的数目。

解答

public class FriendCircle {
    public int findCircleNum(int[][] M){
        int[] fathers = new int[M.length];
        for (int i = 0; i < fathers.length; i++) {
            fathers[i] = i;
        }

        int count = M.length;
        for (int i = 0; i < M.length; i++) {
            for (int j = i + 1; j < M.length; j++) {
                if (M[i][j] == 1 && union(fathers, i, j)){
                    count--;
                }

            }

        }
        return count;
    }

    private int findFather(int[] fathers, int i){
        if (fathers[i] != i)
            fathers[i] = findFather(fathers, fathers[i]);
        return fathers[i];
    }

    private boolean union(int[] fathers, int i, int j) {
        int fatherOfI = findFather(fathers, i);
        int fatherOfJ = findFather(fathers, j);

        if (fatherOfI != fatherOfJ){
            fathers[fatherOfI] = fathers[fatherOfJ];
            return true;
        }
        return false;
    }

}
posted @ 2022-04-06 11:42  叶拂衣  阅读(181)  评论(0)    收藏  举报