File tree Expand file tree Collapse file tree 2 files changed +58
-67
lines changed Expand file tree Collapse file tree 2 files changed +58
-67
lines changed Load Diff This file was deleted.
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int findCircleNum (int [][] isConnected ) {
3
+ UnionFind uf = new UnionFind (isConnected .length );
4
+
5
+ for (int row = 0 ; row < isConnected .length ; row ++) {
6
+ for (int col = 0 ; col < isConnected [row ].length ; col ++) {
7
+ if (isConnected [row ][col ] == 1 ) {
8
+ uf .union (row , col );
9
+ }
10
+ }
11
+ }
12
+
13
+ return uf .noOfComponents ;
14
+ }
15
+
16
+ private class UnionFind {
17
+ private int [] parents , counts ;
18
+ private int noOfComponents ;
19
+
20
+ public UnionFind (int n ) {
21
+ noOfComponents = n ;
22
+ parents = new int [n ];
23
+ counts = new int [n ];
24
+
25
+ for (int i = 0 ; i < parents .length ; i ++) {
26
+ parents [i ] = i ;
27
+ counts [i ] = 1 ;
28
+ }
29
+ }
30
+
31
+ public int find (int node ) {
32
+ if (parents [node ] == node ) {
33
+ return node ;
34
+ }
35
+
36
+ parents [node ] = find (parents [parents [node ]]);
37
+ return parents [node ];
38
+ }
39
+
40
+ public void union (int i , int j ) {
41
+ int p1 = find (i ), p2 = find (j );
42
+
43
+ if (p1 == p2 ) {
44
+ return ;
45
+ }
46
+
47
+ if (counts [p1 ] > counts [p2 ]) {
48
+ parents [p2 ] = p1 ;
49
+ counts [p1 ] += counts [p2 ];
50
+ } else {
51
+ parents [p1 ] = p2 ;
52
+ counts [p2 ] += counts [p1 ];
53
+ }
54
+
55
+ --noOfComponents ;
56
+ }
57
+ }
58
+ }
You can’t perform that action at this time.
0 commit comments