Given a non-empty 2D array grid
of 0's and 1's, an island is a group of 1
's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
Example:
[[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]]
return 6
这道题看似有点像最短步数问题,于是一开始先用动态规划做,然而发现会有重复计算,当上下左右四角都是1时,右下角的1会计算两次左上角的1。于是改用DFS。
public class MaxAreaOfIsland_0695 {
public int maxAreaOfIsland(int[][] grid) {
if (grid.length < 1 || grid[0].length < 1) {
return 0;
}
int max = 0;
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
max = Math.max(max, deepS(grid,i,j));
}
}
return max;
}
public int deepS(int[][] nums, int i, int j){
if(i >=0 && i <nums.length && j >=0 && j < nums[0].length && nums[i][j] == 1 ){
nums[i][j] = 0;
return 1+deepS(nums, i+1,j)+deepS(nums, i, j+1) + deepS(nums, i-1, j) + deepS(nums, i, j-1);
}else{
return 0;
}
}
}