forked from seanprashad/leetcode-patterns
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path547_Number_of_Provinces.java
58 lines (47 loc) · 1.44 KB
/
547_Number_of_Provinces.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
classSolution {
publicintfindCircleNum(int[][] isConnected) {
UnionFinduf = newUnionFind(isConnected.length);
for (introw = 0; row < isConnected.length; row++) {
for (intcol = 0; col < isConnected[row].length; col++) {
if (isConnected[row][col] == 1) {
uf.union(row, col);
}
}
}
returnuf.noOfComponents;
}
privateclassUnionFind {
privateint[] parents, counts;
privateintnoOfComponents;
publicUnionFind(intn) {
noOfComponents = n;
parents = newint[n];
counts = newint[n];
for (inti = 0; i < parents.length; i++) {
parents[i] = i;
counts[i] = 1;
}
}
publicintfind(intnode) {
if (parents[node] == node) {
returnnode;
}
parents[node] = find(parents[parents[node]]);
returnparents[node];
}
publicvoidunion(inti, intj) {
intp1 = find(i), p2 = find(j);
if (p1 == p2) {
return;
}
if (counts[p1] > counts[p2]) {
parents[p2] = p1;
counts[p1] += counts[p2];
} else {
parents[p1] = p2;
counts[p2] += counts[p1];
}
--noOfComponents;
}
}
}