leetcode_695_岛屿的最大面积

给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。

找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)

示例 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]]

对于上面这个给定矩阵应返回 6。注意答案不应该是11,因为岛屿只能包含水平或垂直的四个方向的‘1’。

示例 2:

[[0,0,0,0,0,0,0,0]]

对于上面这个给定的矩阵, 返回 0

注意: 给定的矩阵grid 的长度和宽度都不超过 50。


class Solution {
public:
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        int area=0;
        int temp=0;
        for(int i=0;i<grid.size();i++){
            for(int j=0;j<grid[0].size();j++){
                if(grid[i][j]==1){
                    temp=calcMax(grid,i,j);
                    area=max(area,temp);
                }
            }
        }
        return area;
    }
    
   int calcMax(vector<vector<int>>& grid,int i,int j){
        int n = 1;
        grid[i][j] = 0;
        if(i+1<grid.size() && grid[i+1][j] == 1){
            n += calcMax(grid, i+1, j);
        }
        if(j+1<grid[0].size() && grid[i][j+1] == 1){
            n += calcMax(grid, i, j+1);
        }
        if(i-1>=0 && grid[i-1][j] == 1){
            n += calcMax(grid, i-1, j);
        }
        if(j-1>=0 && grid[i][j-1] == 1){
            n += calcMax(grid, i, j-1);
        }
        return n;
    }
    
};
此方法为递归调用,检测为1的上下左右,并把1置0
class Solution {
public:
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        int m=grid.size(), n=grid[0].size();
        int max_a=0;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j]==1){
                    int a = islandDFS(grid, m, n, i, j);
                    max_a = max(max_a, a);
                }
            }
        }
        return max_a;
    }

    int islandDFS(vector<vector<int>>& grid, int& m, int& n, int i, int j){
        if (i<0 || i>=m || j<0 || j>=n || grid[i][j]==0)
            return 0;
        else{
            grid[i][j] = 0;
            return 1+islandDFS(grid, m, n, i+1, j)+islandDFS(grid, m, n, i-1, j)+
                   islandDFS(grid, m, n, i, j+1)+islandDFS(grid, m, n, i, j-1);
        }
    }
};
这两种方法思想一样,只不过实现方式有区别



;