File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change @@ -23,4 +23,47 @@ private void dfs(int[][] M, int i) {
23
23
}
24
24
}
25
25
}
26
+
27
+ public int findCircleNum2 (int [][] M ) {
28
+ int n = M .length ;
29
+ UnionFind uf = new UnionFind (n );
30
+ for (int i = 0 ; i < n ; i ++) {
31
+ for (int j = i + 1 ; j < n ; j ++) {
32
+ if (M [i ][j ] == 1 ) {
33
+ uf .union (i , j );
34
+ }
35
+ }
36
+ }
37
+ return uf .count ();
38
+ }
39
+
40
+ class UnionFind {
41
+ int [] path ;
42
+ int count ;
43
+
44
+ public UnionFind (int n ) {
45
+ path = new int [n ];
46
+ count = n ;
47
+ for (int i = 0 ; i < n ; i ++) {
48
+ path [i ] = i ;
49
+ }
50
+ }
51
+
52
+ public int find (int i ) {
53
+ while (i != path [i ]) i = path [i ];
54
+ return i ;
55
+ }
56
+
57
+ public void union (int i , int j ) {
58
+ int rootI = find (i );
59
+ int rootJ = find (j );
60
+ if (rootI == rootJ ) return ;
61
+ path [rootI ] = rootJ ;
62
+ count --;
63
+ }
64
+
65
+ public int count () {
66
+ return count ;
67
+ }
68
+ }
26
69
}
You can’t perform that action at this time.
0 commit comments