1
+ class Solution {
2
+ public List <Integer > numIslands2 (int m , int n , int [][] positions ) {
3
+ int x [] = { -1 , 1 , 0 , 0 };
4
+ int y [] = { 0 , 0 , -1 , 1 };
5
+
6
+ UnionFind dsu = new UnionFind (m * n );
7
+
8
+ List <Integer > answer = new ArrayList <>();
9
+
10
+ for (int [] position : positions ) {
11
+
12
+ int landPosition = position [0 ] * n + position [1 ];
13
+
14
+ dsu .addLand (landPosition );
15
+
16
+ for (int i = 0 ; i < 4 ; i ++) {
17
+
18
+ int neighborX = position [0 ] + x [i ];
19
+ int neighborY = position [1 ] + y [i ];
20
+
21
+ int neighborPosition = neighborX * n + neighborY ;
22
+
23
+ if (neighborX >= 0 && neighborX < m && neighborY >= 0 && neighborY < n && dsu .isLand (neighborPosition )) {
24
+
25
+ dsu .union (landPosition , neighborPosition );
26
+
27
+ }
28
+ }
29
+
30
+ answer .add (dsu .numberOfIslands ());
31
+
32
+ }
33
+
34
+ return answer ;
35
+ }
36
+ }
37
+
38
+ class UnionFind {
39
+
40
+ int [] parent ;
41
+ int [] rank ;
42
+
43
+ int count ;
44
+
45
+ public UnionFind (int size ) {
46
+
47
+ parent = new int [size ];
48
+ rank = new int [size ];
49
+
50
+ for (int i = 0 ; i < size ; i ++) {
51
+
52
+ parent [i ] = -1 ;
53
+
54
+ }
55
+
56
+ count = 0 ;
57
+ }
58
+
59
+ public void addLand (int x ) {
60
+
61
+ if (parent [x ] >= 0 ) {
62
+ return ;
63
+ }
64
+
65
+ parent [x ] = x ;
66
+ count ++;
67
+
68
+ }
69
+
70
+ public boolean isLand (int x ) {
71
+
72
+ if (parent [x ] >= 0 ) {
73
+ return true ;
74
+ } else {
75
+ return false ;
76
+ }
77
+
78
+ }
79
+
80
+ int numberOfIslands () {
81
+ return count ;
82
+ }
83
+
84
+ public int find (int x ) {
85
+
86
+ if (parent [x ] != x ) {
87
+ parent [x ] = find (parent [x ]);
88
+ }
89
+
90
+ return parent [x ];
91
+
92
+ }
93
+
94
+ public void union (int x , int y ) {
95
+
96
+ int xset = find (x );
97
+ int yset = find (y );
98
+
99
+ if (xset == yset ) {
100
+ return ;
101
+ } else if (rank [xset ] < rank [yset ]) {
102
+ parent [xset ] = yset ;
103
+ } else if (rank [xset ] > rank [yset ]) {
104
+ parent [yset ] = xset ;
105
+ } else {
106
+ parent [yset ] = xset ;
107
+ rank [xset ]++;
108
+ }
109
+
110
+ count --;
111
+
112
+ }
113
+ }
0 commit comments