1
+ package question0827_making_a_large_island ;
2
+
3
+ import java .util .HashSet ;
4
+ import java .util .Set ;
5
+
6
+ public class Solution {
7
+
8
+ private static class UnionFind {
9
+
10
+ int [] parent ;
11
+
12
+ int n ;
13
+
14
+ int setCount ;
15
+
16
+ public UnionFind (int n ) {
17
+ this .n = n ;
18
+ this .parent = new int [n ];
19
+ this .setCount = n ;
20
+ for (int i = 0 ; i < n ; ++i ) {
21
+ parent [i ] = i ;
22
+ }
23
+ }
24
+
25
+ public int findParent (int x ) {
26
+ int a = x ;
27
+ while (x != parent [x ]) {
28
+ x = parent [x ];
29
+ }
30
+ while (a != parent [a ]) {
31
+ int z = parent [a ];
32
+ parent [a ] = x ;
33
+ a = z ;
34
+ }
35
+ return x ;
36
+ }
37
+
38
+ public boolean union (int a , int b ) {
39
+ int aParent = findParent (a ), bParent = findParent (b );
40
+ if (aParent != bParent ) {
41
+ parent [aParent ] = bParent ;
42
+ setCount --;
43
+ return true ;
44
+ }
45
+ return false ;
46
+ }
47
+
48
+ }
49
+
50
+ public int largestIsland (int [][] grid ) {
51
+ int n = grid .length ;
52
+ UnionFind unionFind = new UnionFind (n * n );
53
+ int [][] directions = {{-1 , 0 }, {1 , 0 }, {0 , -1 }, {0 , 1 }};
54
+ for (int i = 0 ; i < n ; i ++) {
55
+ for (int j = 0 ; j < n ; j ++) {
56
+ if (grid [i ][j ] == 1 ) {
57
+ for (int [] direction : directions ) {
58
+ int nextI = i + direction [0 ], nextJ = j + direction [1 ];
59
+ if (nextI >= 0 && nextI < n && nextJ >= 0 && nextJ < n && grid [nextI ][nextJ ] == 1 ) {
60
+ unionFind .union (i * n + j , nextI * n + nextJ );
61
+ }
62
+ }
63
+ }
64
+ }
65
+ }
66
+ int [] count = new int [n * n ];
67
+ for (int i = 0 ; i < unionFind .parent .length ; i ++) {
68
+ count [unionFind .findParent (i )]++;
69
+ }
70
+ int result = 0 ;
71
+ for (int i = 0 ; i < count .length ; i ++) {
72
+ result = Math .max (result , count [i ]);
73
+ }
74
+ for (int i = 0 ; i < n ; i ++) {
75
+ for (int j = 0 ; j < n ; j ++) {
76
+ if (grid [i ][j ] == 0 ) {
77
+ int temp = 1 ;
78
+ Set <Integer > set = new HashSet <>();
79
+ for (int [] direction : directions ) {
80
+ int nextI = i + direction [0 ], nextJ = j + direction [1 ];
81
+ if (nextI >= 0 && nextI < n && nextJ >= 0 && nextJ < n && grid [nextI ][nextJ ] == 1 ) {
82
+ int parent = unionFind .findParent (nextI * n + nextJ );
83
+ if (!set .contains (parent )) {
84
+ temp += count [parent ];
85
+ set .add (parent );
86
+ }
87
+ }
88
+ }
89
+ result = Math .max (result , temp );
90
+ }
91
+ }
92
+ }
93
+ return result ;
94
+ }
95
+
96
+ public static void main (String [] args ) {
97
+ int [][] grid = {{1 , 0 }, {1 , 1 }};
98
+ System .out .println (new Solution ().largestIsland (grid ));
99
+ }
100
+
101
+ }
0 commit comments