-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
61 lines (51 loc) · 1.33 KB
/
Solution.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
class Solution {
private class UnionFind {
int[] rank;
int[] group;
UnionFind(int n) {
rank = new int[n];
group = new int[n];
for (int i = 0; i < n; ++i) {
group[i] = i;
}
}
int find(int k) {
if (group[k] == k) {
return k;
}
return group[k] = find(group[k]);
}
boolean unite(int a, int b) {
int ga = find(a);
int gb = find(b);
if (ga == gb) {
return false;
}
if (rank[ga] < rank[gb]) {
group[ga] = gb;
} else if (rank[gb] < rank[ga]) {
group[gb] = ga;
} else {
group[ga] = gb;
++rank[gb];
}
return true;
}
};
public int findCircleNum(int[][] isConnected) {
int n = isConnected.length;
UnionFind uf = new UnionFind(n);
int result = n;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (isConnected[i][j] == 0) {
continue;
}
if (uf.unite(i, j)) {
--result;
}
}
}
return result;
}
}