class Solution {
public int maxAreaOfIsland(int[][] grid) {
int[][] visited = new int[grid.length][grid[0].length];
int max = 0;
// looping through the grid
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[0].length; j++) {
// if not visited & it's an island
if(visited[i][j] != 1 && grid[i][j] == 1) {
int area = calcArea(grid, i, j, visited);
max = Math.max(max, area);
}
}
}
return max;
}
private int calcArea(int[][] grid, int row, int col, int[][] visited) {
// out of bound
if(row < 0 || row >= grid.length || col < 0 || col >= grid[0].length) {
return 0;
}
// visited before, don't count it again
if(visited[row][col] == 1) {
return 0;
} else {
// mark as visted
visited[row][col] = 1;
}
// water
if(grid[row][col] == 0) {
return 0;
}
// check up, down, bottom, right
return 1 + calcArea(grid, row - 1, col, visited) +
calcArea(grid, row + 1, col, visited)
+ calcArea(grid, row, col - 1, visited) + calcArea(grid, row, col + 1, visited);
}}