dfs搜索一块岛屿的面积,求最大值
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param grid int整型二维数组
* @return int整型
*/
int [][]visited;
int [][]disrs=new int[][]{{0,1},{0,-1},{1,0},{-1,0}};
public int maxAreaIsland (int[][] grid) {
// write code here
int n=grid.length;
int m=grid[0].length;
visited=new int[n][m];
int maxSquare=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(grid[i][j]!='0'&&visited[i][j]!=1){
maxSquare=Math.max(dfs(grid,i,j,0,n,m),maxSquare);
}
}
}
return maxSquare;
}
int dfs(int [][]grid,int x,int y,int curD,int n,int m){
int square=0;
if(x<0||x>=n||y<0||y>=m){
return 0;
}
if(grid[x][y]==0)
return 0;
if(visited[x][y]==1){
return 0;
}
visited[x][y]=1;
square++;
for(int i=0;i<4;i++){
int nextX=x+disrs[curD][0];
int nextY=y+disrs[curD][1];
square+=dfs(grid,nextX,nextY,curD,n,m);
curD=(curD+1)%4;
}
return square;
}
}