Skip to content

Commit 4c5f474

Browse files
committed
number of connected components in an undirected graph solution
1 parent fd2a43c commit 4c5f474

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import java.util.*;
2+
3+
public class Solution {
4+
5+
// Union Find
6+
public int countComponents(int n, int[][] edges) {
7+
8+
List<Integer> parent = clearGraph(n);
9+
10+
for (int[] edge : edges) {
11+
union(parent, edge[0], edge[1]);
12+
}
13+
14+
Set<Integer> componentRoots = new HashSet<>();
15+
for (int i = 0; i < n; i++) {
16+
componentRoots.add(find(parent, i));
17+
}
18+
19+
return componentRoots.size();
20+
}
21+
22+
private void union(List<Integer> parent, int x, int y) {
23+
int px = find(parent, x);
24+
int py = find(parent, y);
25+
if (px > py) {
26+
parent.set(py, px);
27+
} else {
28+
parent.set(px, py);
29+
}
30+
}
31+
32+
private int find(List<Integer> parent, int x) {
33+
if (parent.get(x) == x) {
34+
return x;
35+
}
36+
parent.set(x, find(parent, parent.get(x)));
37+
return parent.get(x);
38+
}
39+
40+
private List<Integer> clearGraph(int n) {
41+
List<Integer> parent = new ArrayList<>();
42+
for (int i = 0; i < n; i++) {
43+
parent.add(i);
44+
}
45+
return parent;
46+
}
47+
}
48+
49+

0 commit comments

Comments
 (0)