1.描述
给定一个二维数组,找到垂直或水平方向连续1最多的个数,也就是岛的面积。
例如给定二维数组:
[[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最多的岛面积为6.
2.代码:
class Solution{
public int maxAreaOfIsland(int [][] grid){
int res = 0;
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid.length; j++){
if(grid[i][j] == 1) res = Math.max(res, helper(grid, i, j));
}
}
return res;
}
public int helper(int [][] grid, int r, int c){
if(r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) return 0;
int res = 0;
if(grid[r][c] == 1){
//去除已经扫描过的1
grid[r][c] = 0;
res = 1 + helper(grid, r-1, c) + helper(grid, r+1, c) + helper(grid, r, c-1) + helper(grid, r, c+1);
}
return res;
}
}