-
Notifications
You must be signed in to change notification settings - Fork 8
/
FriendCircles.java
73 lines (65 loc) · 1.82 KB
/
FriendCircles.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package unionfind;
// Source : https://leetcode.com/problems/friend-circles/
// Id : 547
// Author : Fanlu Hai | https://github.com/Fanlu91/FanluLeetcode
// Date : 2020-01-01
// Topic : Union Find
// Level : Medium
// Other :
// Tips :
// Result : 99.93% 96.00%
public class FriendCircles {
public int findCircleNum(int[][] M) {
int n = M.length;
UoinFind uoinFind = new UoinFind(n);
for (int i = 0; i < n; i++) {
// check i with i+1 ... n-1
for (int j = i + 1; j < n; j++) {
if (M[i][j] == 1)
uoinFind.union(i, j);
}
}
return uoinFind.count;
}
class UoinFind {
int[] parent;
int[] size;
int count;
public UoinFind(int n) {
this.parent = new int[n];
this.size = new int[n];
this.count = n;
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ)
return;
if (size[rootP] > size[rootQ]) {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
} else {
parent[rootP] = rootQ;
size[rootQ] += size[p];
}
count--;
}
public int find(int n) {
while (parent[n] != n) {
// 进行路径压缩
parent[n] = parent[parent[n]];
n = parent[n];
}
return n;
}
public boolean connected(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
return rootP == rootQ;
}
}
}