DFS解决,核心:递归的时候注意把当前找到的岛屿置零~
public int maxAreaOfIsland(int[][] grid) {
int res = 0;
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[i].length;j++){
if(grid[i][j]==1){
res = Math.max(helper(i,j,grid),res);
}
}
}
return res;
}
public int helper(int i,int j,int[][] grid){
if(i<0||j<0||i>=grid.length||j>=grid[i].length||grid[i][j]==0){
return 0;
}
grid[i][j]=0;//核心
int num = 1;//是岛屿的默认个数为1
num+=helper(i,j+1,grid);
num+=helper(i,j-1,grid);
num+=helper(i-1,j,grid);
num+=helper(i+1,j,grid);
return num;
}