Leetcode | Max Area of Island

原题链接:https://leetcode.com/problems/max-area-of-island

原题意内容如下所示:

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 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’组成的块,有多少个1这个岛屿的面积就是多少,求出这些岛屿中的最大面积。

这道题可以将它转化为求一个图中最大连通块的大小的问题,图中有很多孤立的岛屿,即存在很多连通块,我们需要遍历整个图来找到连通块的入口,再从入口处做一遍深度优先遍历求出相应岛屿的大小,最后再比较各岛屿求出最大岛屿的大小。

这里比较关键的一点就是在DFS过程中记录已访问过的岛屿上的点,我是通过visited这个数组来进行记录,若还没访问过,就置为0,若访问过就置为1。

根据上述思想,给出源代码如下所示:

class Solution {
public:
    void dfs(int i, int j, int& area, vector<vector<int>>& grid) {
        visited[i][j] = 1;
        int n = grid.size();
        int col = grid[i].size();
        if (i-1 >= 0 && !visited[i-1][j] && grid[i-1][j]) {
            dfs(i-1, j, ++area, grid);
        }
        if (j-1 >= 0 && !visited[i][j-1] && grid[i][j-1]) {
            dfs(i, j-1, ++area, grid);
        }
        if (i+1 < n && !visited[i+1][j] && grid[i+1][j]) {
            dfs(i+1, j, ++area, grid);
        }
        if (j+1 < col && !visited[i][j+1] && grid[i][j+1]) {
            dfs(i, j+1, ++area, grid);
        }
    }
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        int max = 0;        
        for (int i = 0; i < 50; i++) {
            for(int j = 0; j < 50; j++) {
                visited[i][j] = 0;
            }
        }
        for (int i = 0; i < grid.size(); i++) {
            for (int j = 0; j < grid[i].size(); j++) {
                int area = 0;
                if (!visited[i][j] && grid[i][j]) dfs(i, j, ++area, grid);
                if (max < area) max = area;
            }
        }
        return max;
    }
private:
    bool visited[50][50];
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值