思路:dfs。每次遇到岛屿就把岛屿清零,用size记住清除的次数即可。
public class Solution {
int maxSize;
int size;
public int maxAreaIsland (int[][] grid) {
for(int i=0;i<grid.length;++i)
for(int j=0;j<grid[0].length;++j){
if(grid[i][j]==1){
clear(grid,i,j);
}
size = 0;
}
return maxSize;
}
public void clear(int[][]grid,int i,int j){
if(size>maxSize)maxSize = size;
if(i>=0&&i<grid.length&&j>=0&&j<grid[0].length&&grid[i][j]==1){
size+=1;
grid[i][j] = 0;
clear(grid,i+1,j);
clear(grid,i-1,j);
clear(grid,i,j+1);
clear(grid,i,j-1);
}
}
}