Leetcode第695题. Max Area of Island
来源:互联网 发布:android7源码 编辑:程序博客网 时间:2024/05/22 02:20
原题地址如下:https://leetcode.com/problems/max-area-of-island/description/
使用深度优先搜索的方案
class Solution {public: int maxAreaOfIsland(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(), ans = 0; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if (grid[i][j] == 1) ans = max(ans, dfs(grid, i, j));//当前结点的值为1才深度优先遍历 return ans; }private: int dfs(vector<vector<int>>& grid, int row, int col) { int m = grid.size(), n = grid[0].size(), area = 1;//一旦进入 因为当前结点的值为1 首先将其对应的area设为1 grid[row][col] = 0;//将这个点的值设为2 因为这个点已经被处理过了 vector<int> dir({-1,0,1,0,-1});//这是一个巧妙的设置遍历上下左右的点的方式 减少代码书写 for (int i = 0; i < 4; i++) { int r = row+dir[i], c = col+dir[i+1];//依次遍历当前处理结点的上,右,下,左四个点 if (r >= 0 && r < m && c >= 0 && c < n && grid[r][c] == 1) //结点在范围内 且该节点的值为1 排除所有为0的点以及访问过的点 避免重复 area += dfs(grid, r, c); } return area; }};
这道题目的关键在于设置当前结点的面积area的计算方案上。在遍历四周结点的同时,需要考虑到排除重复搜索的问题:
- 如果当前结点值为0 直接跳过。
- 如果当前结点的值为2(任意不为1值)代表这个结点已经在之前处理过了:有可能是直接遍历过了这个点,也有可能是在求解其他的点的面积的时候遍历过了这个点。总之这些点是属于其他的联通集合,我们就不需要再对这些点进行处理。一个是减少搜索的重复,二是可以直接避免重复计算。
阅读全文
0 0
- Leetcode第695题. Max Area of Island
- leetcode 695(Max Area of Island)
- leetcode 695 Max Area of Island
- LeetCode: Max Area of Island
- Max Area of Island(leetcode)
- leetCode-Max Area of Island
- 695 Max Area of Island
- LeetCode算法题——Max Area of Island
- leetcode 695. Max Area of Island 解法
- [LeetCode] Algorithms-695. Max Area of Island
- Leetcode 695. Max Area of Island
- LeetCode-695. Max Area of Island
- LeetCode 695. Max Area of Island
- LeetCode-695. Max Area of Island
- [LeetCode] 695. Max Area of Island
- 【LeetCode】695. Max Area of Island
- 695. Max Area of Island
- 695. Max Area of Island
- 【Java】【网络编程】Socket
- sentos yum安装mysql
- CentOS安装JDK的三种方法
- Ajax跨域请求后台无法识别session id的解决方式[withCredentials = true]
- jdk安装与环境变量配置、Scala编译器安装、IDEA安装Scala插件
- Leetcode第695题. Max Area of Island
- 对LSTM中M(Memory)的再思考
- 【腾讯TMQ】移动设备管理控制工具(STF)平台的正确搭建方式
- 51nod 1650 穿越无人区 (找规律)
- Java课程学习十一:图片匹配游戏
- Tensor
- 百度NLP架构与应用
- PE文件框架结构图
- LintCode之6 合并排序数组