Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
Copy [[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Note the answer is not 11, because the island must be connected 4-directionally.
Copy class Solution {
public int maxAreaOfIsland ( int [][] grid) {
if (grid == null || grid . length == 0 ) {
return 0 ;
}
int m = grid . length , n = grid[ 0 ] . length ;
int [][] directions = {{ - 1 , 0 } , { 1 , 0 } , { 0 , - 1 } , { 0 , 1 }};
UnionFind uf = new UnionFind(grid) ;
for ( int i = 0 ; i < m; i ++ ) {
for ( int j = 0 ; j < n; j ++ ) {
if (grid[i][j] == 1 ) {
for ( int [] direction : directions) {
int nextRow = i + direction[ 0 ];
int nextCol = j + direction[ 1 ];
if ( isValid(nextRow , nextCol , grid) ) {
int id1 = i * n + j;
int id2 = nextRow * n + nextCol;
uf . union (id1 , id2);
}
}
}
}
}
return uf . maxArea ();
}
public boolean isValid ( int row , int col , int [][] grid) {
return row >= 0 && row < grid . length && col >= 0 && col < grid[ 0 ] . length && grid[row][col] == 1 ;
}
class UnionFind {
int [] sets;
int [] size;
int m , n , count;
public UnionFind ( int [][] grid) {
m = grid . length ;
n = grid[ 0 ] . length ;
sets = new int [m * n];
size = new int [m * n];
for ( int i = 0 ; i < m; i ++ ) {
for ( int j = 0 ; j < n; j ++ ) {
if (grid[i][j] == 1 ) {
int id = i * n + j;
sets[id] = id;
size[id] = 1 ;
++ count;
}
}
}
}
public int find ( int node) {
while (node != sets[node]) {
node = sets[node];
}
return node;
}
public void union ( int i , int j) {
int node1 = find(i) ;
int node2 = find(j) ;
if (node1 == node2) {
return ;
}
if (size[node1] < size[node2]) {
sets[node1] = node2;
size[node2] += size[node1];
}
else {
sets[node2] = node1;
size[node1] += size[node2];
}
-- count;
}
public int maxArea () {
int res = 0 ;
for ( int i = 0 ; i < size . length ; i ++ ) {
res = Math . max (res , size[i]);
}
return res;
}
}
}