There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.
Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.
Example 1:
Input: [[1,1,0], [1,1,0], [0,0,1]] Output: 2 Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
The 2nd student himself is in a friend circle. So return 2.
Example 2:
Input: [[1,1,0], [1,1,1], [0,1,1]] Output: 1 Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,
so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.
Note:
- N is in range [1,200].
- M[i][i] = 1 for all students.
- If M[i][j] = 1, then M[j][i] = 1.
给定N * N矩阵M代表班级中学生之间的朋友关系。如果M [i] [j] = 1,那么第i和第j个学生是彼此直接的朋友,否则不是。你必须输出所有学生中的朋友圈的总数。
/**
* 加权并查集
*/
class WeightedQuickUnionUF {
constructor(n) {
this.count = n;
this.parent = [];
this.parent.length = n;
this.size = [];
this.size.length = n;
for (let i = 0; i < n; i++) {
this.parent[i] = i;
this.size[i] = 1;
}
}
find(p) {
while (p != this.parent[p]) {
p = this.parent[p];
}
return p;
}
union(p, q) {
let rootP = this.find(p);
let rootQ = this.find(q);
if (rootP == rootQ) return;
if (this.size[rootP] < this.size[rootQ]) {
this.parent[rootP] = rootQ;
this.size[rootQ] += this.size[rootP];
} else {
this.parent[rootQ] = rootP;
this.size[rootP] += this.size[rootQ];
}
this.count--;
}
connented(p, q) {
this.find(p) == this.find(q);
}
}
/**
* @param {number[][]} M
* @return {number}
*/
var findCircleNum = function (M) {
let uf = new WeightedQuickUnionUF(M.length)
for (let i = 0; i < M.length; i++) {
for (let j = 0; j < M[i].length; j++) {
if (M[i][j] == 1) {
uf.union(i, j);
}
}
}
return uf.count;
};
let m = [
[1, 0, 0, 1],
[0, 1, 1, 0],
[0, 1, 1, 1],
[1, 0, 1, 1]
];
let res = findCircleNum(m);
console.log(res);