695. **Max Area of Island

​https://leetcode.com/problems/max-area-of-island/description/​

题目描述

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​​.

题目思路

解法一: 使用深度优先, 递归实现. 首先我们可以求出 ​​grid​​​ 中每一片陆地的面积, 然后从中找到最大的那个. 当我们到达某个陆地区域时(比如 ​​grid[r][c] == 1​​​, 那么我们还要找它四个方向的陆地, 然后所有的被访问区域之和就是整个陆地的面积.
为了保证我们没有将已经访问过的区域重复计算, 可以将对应的 ​​​grid[r][c]​​​ 从 ​​1​​​ 设置为 ​​0​​, 表示已经访问过了.

解法二: 使用迭代, 以后还记得的话过来补充…

C++ 实现 1

使用深度优先, 递归实现. 用递归实现的关键在于找到递归终止的条件. 比如下面递归终止的条件是访问位置超出边界, 或者当前访问的元素 ​​grid[r][c] == 0​​.

class Solution {
private:
int area(vector<vector<int>> &grid, int r, int c) {
if (r < 0 || r >= grid.size() ||
c < 0 || c >= grid[0].size() || grid[r][c] == 0)
return 0;

grid[r][c] = 0;

return (1 + area(grid, r - 1, c)
+ area(grid, r + 1, c)
+ area(grid, r, c - 1)
+ area(grid, r, c + 1));
}
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
if (grid.empty() || grid[0].empty()) return 0;
int rows = grid.size(), cols = grid[0].size();
int res = 0;
for (int i = 0; i < rows; ++ i) {
for (int j = 0; j < cols; ++ j) {
res = std::max(res, area(grid, i, j));
}
}
return res;
}
};