输入:
grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
思路
1、遍历二维数组
2、遇到1,记录,将1改为0防止多记
3、递归步骤2
遍历二维数组
int max = 0;
for(int i = 0;i < grid.length;i++){
for(int j = 0; j < grid[0].length;j++){
if(grid[i][j] == 1){
max = Math.max(serach(grid,i,j),max);
}
}
}
查找方法
public int serach(int grid[][],int i,int j){
if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0){
return 0;
}
//将1改为0
grid[i][j] = 0;
int num = 1;
num += serach(grid,i-1,j);
num += serach(grid,i+1,j);
num += serach(grid,i,j-1);
num += serach(grid,i,j+1);
return num;
}
源代码
public int maxAreaOfIsland(int[][] grid) {
int max = 0;
for(int i = 0;i < grid.length;i++){
for(int j = 0; j < grid[0].length;j++){
if(grid[i][j] == 1){
max = Math.max(serach(grid,i,j),max);
}
}
}
return max;
}
public int serach(int grid[][],int i,int j){
if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0){
return 0;
}
grid[i][j] = 0;
int num = 1;
num += serach(grid,i-1,j);
num += serach(grid,i+1,j);
num += serach(grid,i,j-1);
num += serach(grid,i,j+1);
return num;
}