1
+ class Solution {
2
+ /*
3
+ Same idea like validTree question, here we have to return the count,
4
+ Also, we have to decrement the count, only when a new edge is compressed.
5
+ Hence, we have to put a check that if parent of one node is not equals to
6
+ parent of other, then only we decrement the count.
7
+ [0,1], [1,2] will make a graph with 0 as parent and 1 and 2 as child.
8
+ So, when it encounters, [0,2] edge then, that is already been compressed/unioned
9
+ hence, we need not decrement the count in such case. Hence a way to find out is
10
+ by checking the parent of the nodes.
11
+ */
12
+ public int countComponents (int n , int [][] edges ) {
13
+ UnionFind uf = new UnionFind (n );
14
+ for (int i =0 ; i <edges .length ; i ++) {
15
+ uf .union (edges [i ][0 ], edges [i ][1 ]);
16
+ }
17
+ return uf .count ;
18
+ }
19
+ }
20
+
21
+ class UnionFind {
22
+ int count ;
23
+ int [] parent ;
24
+
25
+ public UnionFind (int n ) {
26
+ this .count = n ;
27
+ parent = new int [n ];
28
+
29
+ for (int i =0 ; i <n ; i ++) {
30
+ parent [i ] = i ;
31
+ }
32
+ }
33
+
34
+ public int find (int p ) {
35
+ while (p != parent [p ]) {
36
+ p = parent [p ];
37
+ }
38
+ return parent [p ];
39
+ }
40
+
41
+ public void union (int p , int q ) {
42
+ int parentP = find (p );
43
+ int parentQ = find (q );
44
+ if (parentP != parentQ ) {
45
+ parent [parentQ ] = parentP ;
46
+ count --;
47
+ }
48
+
49
+ }
50
+
51
+ }
0 commit comments