LeetCode笔记:695. Max Area of Island
问题(Easy):
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,由0和1组成,一个岛是指由1通过四个方向(水平或垂直)组成的一块区域(代表陆地)。你可以假设grid的四边都是水。 找到给出的二维数组中最大区域的岛。(如果没有岛,最大区域就是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]] 给出上面的grid,返回6。注意答案不是11,因为岛必须由四个方向连接。 例2: [[0,0,0,0,0,0,0,0]] 给出上面的grid,返回0。 注意:给出的grid每个方向的长度不会超过50。
思路:
我们遍历二维数组的时候,遇到1了,肯定是要检查上下左右是否依然是1(同时注意不要超出边界),如果检查出某一边是1,则还要进一步继续检查它的上下左右是否是1,这说明我们要通过递归来做,遍历时每遇到一个1,就放到递归中去检测并计算岛屿面积。
此外,为了避免循环计算重复的区域,我们要改变已经计算过的岛屿的位置的值,可以从1改成2。
这种递归方式其实就是一种DFS,遇到一个1,则找遍其四周及四周的四周等等,来计算一个岛屿面积,同时改变找过的1的值,避免重复计算。
代码(C++):
class Solution {
public:
int findLand(vector<vector<int>>& grid, int i, int j) {
grid[i][j] = 2;
int sum = 1;
if (i > 0 && grid[i-1][j] == 1) sum = sum + findLand(grid, i-1, j);
if (i < grid.size()-1 && grid[i+1][j] == 1) sum = sum + findLand(grid, i+1, j);
if (j > 0 && grid[i][j-1] == 1) sum = sum + findLand(grid, i, j-1);
if (j < grid[0].size()-1 && grid[i][j+1] == 1) sum = sum + findLand(grid, i, j+1);
return sum;
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
if (grid.size() == 0) return 0;
int res = 0;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[0].size(); j++) {
if (grid[i][j] == 1) {
int temp = findLand(grid, i, j);
res = max(temp, res);
}
}
}
return res;
}
};
合集:https://github.com/Cloudox/LeetCode-Record
相关文章
- 「Spark从精通到重新入门(一)」Spark 中不可不知的动态优化
- 云时代,我们到底需要怎样的数据库?
- OushuDB 学习经验分享(二):与HAWQ的区别
- Firestorm - 腾讯自研Remote Shuffle Service在Spark云原生场景的实践
- CancerSCEM: 人类癌症单细胞表达图谱数据库
- GT Transceiver中的RX功能块简述
- 我是如何赢得吴恩达首届 Data-centric AI 竞赛的?
- 一文速览 | 对话生成预训练模型
- 《云原生:运用容器、函数计算和数据构建下一代应用》
- SLAM中位姿估计的图优化方法比较
- 我是怎么用MySQL的
- 还在用分页?你out了 !试试 MyBatis 流式查询,真心强大!
- 深入分析 I/O 的工作机制
- WebClient 增删改查一文搞定
- 免费高分辨率遥感卫星数据(5m)下载
- Splunk系列:Splunk数据接入篇(二)
- mysql服务器cpu爆满解决办法
- 清理文本数据
- 分布式数据库如何平衡一致性和读写延迟?
- 通过优化 S3 读取来提高效率和减少运行时间