思路:深度优先遍历,对每个是陆地且未曾访问过的位置进行dfs,统计每次进行dfs时的岛屿面积are,ans=Math.max(ans,are)
code:
class Solution {
public int dir[][]={{0,1},{0,-1},{1,0},{-1,0}};
public boolean vis[][];
public int cows;
public int cols;
public int grid[][];
public int ans=0;
public int are=1;
public int maxAreaOfIsland(int[][] grid) {
cows=grid.length;
if(cows==0)return 0;
cols=grid[0].length;
this.grid=grid;
vis=new boolean[cows][cols];
for(int i=0;i<cows;i++){
for(int j=0;j<cols;j++){
if(!vis[i][j]&&grid[i][j]==1){
dfs(i,j);
ans=Math.max(ans,are);
are=1;
}
}
}
return ans;
}
public void dfs(int i,int j){
vis[i][j]=true;
for(int k=0;k<4;k++){
int newx=i+dir[k][0];
int newy=j+dir[k][1];
if(0<=newx&&newx<cows&&0<=newy&&newy<cols&&!vis[newx][newy]
&&grid[newx][newy]==1){
are=are+1;
dfs(newx,newy);
}
}
}
}