DFS:695. Max Area of Island
来源:互联网 发布:端口参数液晶智能电视 编辑:程序博客网 时间:2024/06/07 19:56
这道题的意思是,给一个表格,由0或者1填充,求相连的1的最大面积。
这道题我开辟了一个和表格一样大的二维数组,用于记录这个点是否已经计算过了。dfs这个函数返回的是,当前点所在的一片1的面积。
class Solution {public: int maxAreaOfIsland(vector<vector<int>>& grid) { int m = grid.size(); int n = grid[0].size(); vector<vector<int>> ischeck(m, vector<int>(n, 0)); int res = 0; for(int i = 0; i < m; ++i) { for(int j = 0; j < n; ++j) { res = max(res, dfs(grid, ischeck, i, j)); } } return res; } int dfs(vector<vector<int>>& grid, vector<vector<int>>& ischeck, int i, int j) { int num = 0; if(i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size()) return 0; if(ischeck[i][j] == 0 && grid[i][j] == 1) { ischeck[i][j] = 1; num += 1; num += dfs(grid, ischeck, i+1, j); num += dfs(grid, ischeck, i-1, j); num += dfs(grid, ischeck, i, j+1); num += dfs(grid, ischeck, i, j-1); } return num; }};讨论区一个java代码:
public int maxAreaOfIsland(int[][] grid) { int max_area = 0; for(int i = 0; i < grid.length; i++) for(int j = 0; j < grid[0].length; j++) if(grid[i][j] == 1)max_area = Math.max(max_area, AreaOfIsland(grid, i, j)); return max_area; } public int AreaOfIsland(int[][] grid, int i, int j){ if( i >= 0 && i < grid.length && j >= 0 && j < grid[0].length && grid[i][j] == 1){ grid[i][j] = 0; return 1 + AreaOfIsland(grid, i+1, j) + AreaOfIsland(grid, i-1, j) + AreaOfIsland(grid, i, j-1) + AreaOfIsland(grid, i, j+1); } return 0; }
阅读全文
0 0
- DFS:695. Max Area of Island
- leetcode 695. Max Area of Island 深度优先遍历DFS
- 695. Max Area of Island
- 695. Max Area of Island
- 695. Max Area of Island
- 695. Max Area of Island
- 695. Max Area of Island
- 695. Max Area of Island
- 695. Max Area of Island
- LWC 53:695. 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
- 695. Max Area of Island Difficulty: Easy
- LeetCode 695. Max Area of Island
- LeetCode-695. Max Area of Island
- [LeetCode] 695. Max Area of Island
- Wannafly挑战赛1B-(二分)
- java并发基础(七)--- 加速比、线程开销、减少锁竞争
- 1_电脑知识积累
- Qt: error link1158 无法运行rc.exe
- implements Runnable与extends Thread 的区别
- DFS:695. Max Area of Island
- Linux下 PyopenGL运行libGL报错,解决方案
- Mac上第一个eclipse编译的Hadoop程序
- 用c2制作游戏~
- 深度网络模型压缩
- linux下并行运行脚本与让程序可靠运行
- Fibonacci数列
- PC端不同浏览器的兼容问题及解决方案
- HTML5头部——meta