695. Max Area of Island
Last updated
Last updated
/**
* Time complexity : O(R*C), where R is the number of rows in the given grid,
* and C is the number of columns. We visit every square once.
* Space complexity : O(R*C), the space used by seen to keep track of
* visited squares, and the space used by stack.
*/
class Solution {
public int maxAreaOfIsland(int[][] grid) {
int maxArea = 0;
if(grid != null && grid.length != 0) {
int rows = grid.length, cols = grid[0].length;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if(grid[i][j] == 1) {
maxArea = Math.max(maxArea, calcArea(grid, i, j));
}
}
}
}
return maxArea;
}
private int calcArea(int[][] grid, int x, int y) {
if(x < 0 || x >= grid.length ||
y < 0 || y >= grid[0].length || grid[x][y] != 1) {
return 0;
}
grid[x][y] = 2;
return 1 + calcArea(grid, x-1, y) + calcArea(grid, x, y+1) +
calcArea(grid, x+1, y) + calcArea(grid, x, y-1);
}
}