-
Notifications
You must be signed in to change notification settings - Fork 277
/
MaxAreaofIsland.java
36 lines (29 loc) · 963 Bytes
/
MaxAreaofIsland.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
// TC : O(n*m)
public int maxAreaOfIsland(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
int maxArea = 0;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(grid[i][j]==1){
maxArea = Math.max(maxArea, getCurrentArea(i,j, grid));
}
}
}
return maxArea;
}
private int getCurrentArea(int i,int j, int[][] grid){
if(i<0 || j<0 || i>=grid.length || j>=grid[0].length || grid[i][j]<=0){
return 0;
}
// grid[i][j] = 1
grid[i][j]=-1;
int leftArea = getCurrentArea(i,j-1, grid);
int rightArea = getCurrentArea(i,j+1, grid);
int upArea = getCurrentArea(i-1,j, grid);
int downArea = getCurrentArea(i+1,j, grid);
int totalArea = 1 + leftArea + rightArea +upArea+downArea;
return totalArea;
}
}