File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ package Union_Find ;
2
+
3
+ // Problem Statement: Number of Provinces (medium)
4
+ // LeetCode Question: 547. Number of Provinces
5
+
6
+ public class Problem_2_Number_Of_Provinces {
7
+ private int [] parent ;
8
+
9
+ public int findProvinces (int [][] isConnected ){
10
+ int n = isConnected .length ;
11
+ parent = new int [n ];
12
+ for (int i = 0 ; i < n ; i ++) {
13
+ parent [i ] = i ;
14
+ }
15
+ int provinces = n ;
16
+ for (int i = 0 ; i < n ; i ++) {
17
+ for (int j = i + 1 ; j < n ; j ++) {
18
+ if (isConnected [i ][j ] == 1 && find (i ) != find (j )) {
19
+ union (i , j );
20
+ provinces --;
21
+ }
22
+ }
23
+ }
24
+ return provinces ;
25
+ }
26
+
27
+ private int find (int i ) {
28
+ if (parent [i ] != i ) {
29
+ parent [i ] = find (parent [i ]);
30
+ }
31
+ return parent [i ];
32
+ }
33
+
34
+ private void union (int i , int j ) {
35
+ parent [find (i )] = find (j );
36
+ }
37
+ }
You can’t perform that action at this time.
0 commit comments