Skip to content

Commit 0e644d6

Browse files
authored
Merge pull request neetcode-gh#488 from hogo6002/patch-1
Add JAVA solution for Question 323
2 parents e8fdc3d + 31cec75 commit 0e644d6

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class Solution {
2+
private int[] parent;
3+
private int[] rank;
4+
5+
public int countComponents(int n, int[][] edges) {
6+
parent = new int[n];
7+
rank = new int[n];
8+
9+
for (int i = 0; i < n; i++) {
10+
parent[i] = i;
11+
rank[i] = 1;
12+
}
13+
14+
int result = n;
15+
for (int i = 0; i < edges.length; i++) {
16+
if (union(edges[i][0], edges[i][1]) == 1) {
17+
result--;
18+
}
19+
}
20+
21+
return result;
22+
}
23+
24+
private int find(int node) {
25+
int result = node;
26+
27+
while (parent[result] != result) {
28+
parent[result] = parent[parent[result]];
29+
result = parent[result];
30+
}
31+
32+
return result;
33+
}
34+
35+
private int union(int n1, int n2) {
36+
int p1 = this.find(n1);
37+
int p2 = this.find(n2);
38+
39+
if (p1 == p2) {
40+
return 0;
41+
}
42+
43+
if (rank[p2] > rank[p1]) {
44+
parent[p1] = p2;
45+
rank[p2] += rank[p1];
46+
} else {
47+
parent[p2] = p1;
48+
rank[p1] += rank[p2];
49+
}
50+
51+
return 1;
52+
}
53+
}

0 commit comments

Comments
 (0)