this is a classic flood fill algorithm related problems.
4 way dfs, but why the fuck code is not working?
class Solution {
private int count = 0;
public int maxAreaOfIsland(int[][] grid) {
if(grid == null || grid.length == 0) return 0;
int res = 0;
int row = grid.length;
int col = grid[0].length;
for(int i = 0; i<row; i++){
for(int j = 0; j<col; j++){
if(grid[i][j] == 1){
helper(grid, i, j); //helper indicates the area expand from (i,j): int
res = Math.max(res, count);
count = 0;
}
}
}
return res;
}
private int helper(int[][] grid, int i, int j){
if(grid[i][j] == 1){
grid[i][j] = 0;
count++;
if(i>0 && grid[i-1][j] == 1){ //only goes one way or maybe more way will decide whether to use if/if/if or if/else if/else if
return helper(grid, i - 1, j);
}
if(i<grid.length - 1 && grid[i+1][j] == 1){
return helper(grid, i + 1, j);
}
if(j>0 && grid[i][j-1] == 1){
return helper(grid, i, j - 1);
}
if(j<grid[0].length - 1 && grid[i][j+1] == 1){
return helper(grid, i, j + 1);
}
}
return 0;
}
}
well, now I know why previous code is not working: you can’t return helper(grid, i-1, j)!!! instead, you need to make sure you go all the way to the bottom of the recursion and return! which means, it’s wrong to return sth before you reached the bottom level.