File tree 1 file changed +53
-0
lines changed
1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int removeStones (int [][] stones ) {
3
+ UnionFind uf = new UnionFind (stones .length );
4
+ for (int i =0 ; i <stones .length ; i ++) { // comparing any two points from the stones array
5
+ for (int j =i +1 ; j < stones .length ; j ++) {
6
+ if (stones [i ][0 ] == stones [j ][0 ] || stones [i ][1 ] == stones [j ][1 ]) { // same row or same column for both the points
7
+ uf .union (i , j ); //unioning the points
8
+ }
9
+ }
10
+ }
11
+ return stones .length - uf .count ;
12
+ }
13
+ }
14
+
15
+ class UnionFind {
16
+ int count ;
17
+ int [] parent ;
18
+ int [] size ; // used for union by rank for optimization
19
+
20
+ public UnionFind (int n ) {
21
+ this .count = n ;
22
+ parent = new int [n ];
23
+ size = new int [n ];
24
+
25
+ for (int i =0 ; i <n ; i ++) {
26
+ parent [i ] = i ;
27
+ }
28
+ }
29
+
30
+ public int find (int x ) {
31
+ while (parent [x ] != x ) {
32
+ x = parent [x ];
33
+ }
34
+ return x ;
35
+ }
36
+
37
+ public void union (int p , int q ) {
38
+ int pParent = find (p );
39
+ int qParent = find (q );
40
+ if (pParent == qParent ) {
41
+ return ;
42
+ }
43
+
44
+ if (size [pParent ] <= size [qParent ]) { // union by rank, higher size ones becomes the overall parent for the smaller ones as well.
45
+ parent [pParent ] = qParent ;
46
+ size [qParent ]++;
47
+ } else {
48
+ parent [qParent ] = pParent ;
49
+ size [pParent ]++;
50
+ }
51
+ count --; // every time we union, connected components decreases by 1
52
+ }
53
+ }
You can’t perform that action at this time.
0 commit comments