leetcode 695. Max Area of Island 解法

来源:互联网 发布:java软件设计什么 编辑:程序博客网 时间:2024/06/05 23:42

这是一道求2维图像最大面积的经典题,采用的是深度优先搜索的思路。

原题的例子是:

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.

就是上下左右算相连,求下最大的1的面积。

解法如下:

class Solution {public:    int maxAreaOfIsland(vector<vector<int>>& grid) {        h=grid.size();        if(h == 0)            return 0;        w=grid[0].size();        if(w==0)            return 0;        int max=0;        for(int i=0;i<h;i++)        {            for(int j=0;j<w;j++)            {                if(grid[i][j] == 1)                {                    int s=dfs(grid,i,j);                    if(s>max)                        max =s;                }            }        }        return max;    }    int dfs(vector<vector<int>>& grid,int r, int c)    {        if(r<0||c<0||r>=h||c>=w)            return 0;        if(grid[r][c] ==0)            return 0;        int s=1;        grid[r][c] =0;        s+=dfs(grid,r-1,c);        s+=dfs(grid,r+1,c);        s+=dfs(grid,r,c-1);        s+=dfs(grid,r,c+1);        return s;    }private:    int h;    int w;};

在maxAreaOfIsland函数中,基本的求下图像的宽和高,然后遍历二维数组,找到为1的点,求一下面积。

在dfs函数中,通过递归的方法求面积,其中为防止重复计算,需要把遍历过的1的点设置为0,grid[r][c] =0是递归的关键。