File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change 1+ class UnionFind {
2+ private int [] parents ;
3+ private int circleCount ;
4+
5+ public UnionFind (int n ) {
6+ parents = new int [n ];
7+ for (int i = 0 ; i < n ; i ++) {
8+ parents [i ] = i ;
9+ }
10+ }
11+
12+ public int find (int x ) {
13+ if (parents [x ] == x ) {
14+ return x ;
15+ }
16+
17+ return parents [x ] = find (parents [x ]);
18+ }
19+
20+ public void union (int a , int b ) {
21+ int groupA = find (a );
22+ int groupB = find (b );
23+
24+ if (groupA != groupB ) {
25+ parents [groupA ] = groupB ;
26+ circleCount --;
27+ }
28+ }
29+
30+ public void setCircleCount (int circleCount ) {
31+ this .circleCount = circleCount ;
32+ }
33+
34+ public int getCircleCount () {
35+ return this .circleCount ;
36+ }
37+ }
38+
39+ class Solution {
40+ public int findCircleNum (int [][] M ) {
41+ if (M .length == 0 || M [0 ].length == 0 ) {
42+ return 0 ;
43+ }
44+
45+ int m = M .length ;
46+ int n = M [0 ].length ;
47+
48+ UnionFind unionFind = new UnionFind (m * n );
49+ unionFind .setCircleCount (m );
50+
51+ for (int i = 0 ; i < m ; i ++) {
52+ for (int j = 0 ; j < n ; j ++) {
53+ if (M [i ][j ] == 1 && i != j ) {
54+ unionFind .union (i , j );
55+ }
56+ }
57+ }
58+
59+ return unionFind .getCircleCount ();
60+ }
61+ }
You can’t perform that action at this time.
0 commit comments