[LeetCode] 695. Max Area of Island

来源:互联网 发布:rt809h编程器最新消息 编辑:程序博客网 时间:2024/06/05 21:04

Problem:

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' 的数目最多,如例一,最大面积为第4,5,6行粗体字符 '1' 的数目,即为6。


解题思路:

1. 遍历矩阵(二维数组),对每一个矩阵元素统计"最大面积",通过前后比较得出最终的最大面积

2. 对矩阵中每个元素,通过深度优先搜索计算最大面积


Solution:

class Solution {public:    int maxAreaOfIsland(vector<vector<int>>& grid) {        int height = grid.size();  // 矩阵的高        int width = grid.front().size();    // 矩阵的宽        int maxArea = 0;        for (int i = 0; i < height; i++) {            for (int j = 0; j < width; j++) {                maxArea = max(maxArea, dpsFindMaxArea(grid, i, j));            }        }        return maxArea;    }        // i表示元素的行位置,j表示列位置    int dpsFindMaxArea(vector<vector<int>>& grid, int i, int j) {        // 必须确保不越界        if (i >= 0 && i < grid.size() && j >= 0 && j < grid.front().size()) {            if (grid[i][j] == 1) {                grid[i][j] = 0; //该位置已统计进去,置0                return 1 + dpsFindMaxArea(grid, i-1, j) + dpsFindMaxArea(grid, i+1, j) +                    dpsFindMaxArea(grid, i, j-1) + dpsFindMaxArea(grid, i, j+1);        //统计前后左右的1            }        }        return 0;    }};

深搜时需要注意的点:

1. 由于是通过下标访问矩阵元素,要确保每个元素下标不越界

2. 避免重复统计,统计过的字符'1'需要置0,通过引用访问矩阵

3. 区域内没有字符'1',需要返回0

原创粉丝点击