leetcode 695. Max Area of Island 解法
来源:互联网 发布:java软件设计什么 编辑:程序博客网 时间:2024/06/05 23:42
这是一道求2维图像最大面积的经典题,采用的是深度优先搜索的思路。
原题的例子是:
Example 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],Given the above grid, return[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]]
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
.就是上下左右算相连,求下最大的1的面积。
解法如下:
class Solution {public: int maxAreaOfIsland(vector<vector<int>>& grid) { h=grid.size(); if(h == 0) return 0; w=grid[0].size(); if(w==0) return 0; int max=0; for(int i=0;i<h;i++) { for(int j=0;j<w;j++) { if(grid[i][j] == 1) { int s=dfs(grid,i,j); if(s>max) max =s; } } } return max; } int dfs(vector<vector<int>>& grid,int r, int c) { if(r<0||c<0||r>=h||c>=w) return 0; if(grid[r][c] ==0) return 0; int s=1; grid[r][c] =0; s+=dfs(grid,r-1,c); s+=dfs(grid,r+1,c); s+=dfs(grid,r,c-1); s+=dfs(grid,r,c+1); return s; }private: int h; int w;};
在maxAreaOfIsland函数中,基本的求下图像的宽和高,然后遍历二维数组,找到为1的点,求一下面积。
在dfs函数中,通过递归的方法求面积,其中为防止重复计算,需要把遍历过的1的点设置为0,grid[r][c] =0是递归的关键。
阅读全文
0 0
- 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
- LeetCode: Max Area of Island
- Max Area of Island(leetcode)
- leetCode-Max Area of Island
- 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
- Java面试题集(51-70)
- 相似类型对比
- HDU 5661 Claris and XOR(贪心)
- HDU 3909 Sudoku(数独转DLX精确覆盖)
- Pandas数据排序
- leetcode 695. Max Area of Island 解法
- 学习日志————国庆总结
- 0-1背包问题-回溯&贪心算法-C#Demo
- 51NOD-1011 最大公约数GCD
- 数据结构:实验二线性表综合实验②单链表
- html知识
- 每天一篇博客,绝不断更,以此激励自己
- 10月8日学习笔记
- android studio 设置