力扣第695题:岛屿的最大面积
问题描述
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.
(给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)
)
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
Example 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]]
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
从图中就可以很清楚的知道了。
Example 2:
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0.
Note: The length of each dimension in the given grid does not exceed 50.
问题分析
-
遇到这个问题的时候,我首先就想到了找出最大岛屿,也就是求1连接的最大值。其中岛屿只能包括水平和垂直:DFS——深度遍历;当然,广度遍历也是OK的。
-
每次都去查找1存在的地方,将遍历过的地方区域改变成0,如果想要记住岛屿的位置,也可以将区域改成非1和非0。并记录最大岛屿,用MAX表示最大岛屿个数,函数length()返回每次遍历之后岛屿的长度。
代码如下:
package InterView;
//深度遍历
public class MaxArea {
public int maxAreaOfIsland(int[][] grid) {
int MAX = 0;for (int i=0;i<grid.length;i++){
for(int j=0;j<grid[i].length;j++){
if(grid[i][j] == 1){
MAX = Math.max(MAX,length(grid,i,j));}}}return MAX;}private int length(int[][] grid,int row,int col){
if(row<0 || col<0 || row>=grid.length ||col>=grid[row].length || grid[row][col]==0){
return 0;}grid[row][col] = 0;int num = 1;num +=length(grid,row+1,col);num +=length(grid,row-1,col);num +=length(grid,row,col+1);num +=length(grid,row,col-1);return num;}}