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]]
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}};
int maxArea = 0, area = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
area = getIslandArea(i, j, grid, directions);
maxArea = Math.max(maxArea, area);
}
}
}
return maxArea;
}
public int getIslandArea(int row, int col, int[][] grid, int[][] directions) {
int area = 1;
grid[row][col] = 0;
for (int[] direction : directions) {
int nextRow = row + direction[0];
int nextCol = col + direction[1];
if (isValid(nextRow, nextCol, grid, directions)) {
area += getIslandArea(nextRow, nextCol, grid, directions);
}
}
return area;
}
public boolean isValid(int row, int col, int[][] grid, int[][] directions) {
return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && grid[row][col] == 1;
}
}
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, maxSize;
public UnionFind(int[][] grid) {
m = grid.length;
n = grid[0].length;
sets = new int[m * n];
size = new int[m * n];
maxSize = 0;
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;
maxSize = 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];
maxSize = Math.max(maxSize, size[node2]);
}
else {
sets[node2] = node1;
size[node1] += size[node2];
maxSize = Math.max(maxSize, size[node1]);
}
--count;
}
public int maxArea() {
return maxSize;
}
}
}