File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
number-of-connected-components-in-an-undirected-graph Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments