407. Trapping Rain Water II
来源:互联网 发布:厦门博思软件 编辑:程序博客网 时间:2024/06/05 04:54
Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining.
Note:
Both m and n are less than 110. The height of each unit cell is greater than 0 and is less than 20,000.
Example:Given the following 3x6 height map:[ [1,4,3,1,3,2], [3,2,1,3,2,4], [2,3,3,2,3,1]]Return 4.
这题有点难,一开始打算沿用上一题的思路,找到每个方向上的最大值坐标,根据每个点再最大值上或者下,左或者右,来分析这个点应该被上下左右四个邻居中的哪两个控制增长进水量。后来发现这种条件下改变的状态不具有决定性,周围状态的改变会对这个点的状态继续产生影响,这种思路作罢。
如何计算出具有决定性的状态?这题的讨论区给出了很好的做法,用priority_queue来储存border的所有点,用minheap,这样每次都从边界上的最小值出发,它对它的相邻的点都有决定意义。然后依次扩散,每次都从最小点开始计算。因为这些点的值都不应该再变了,所以他们扩散的影响具有决定意义。
代码:
class cell {public: int row; int col; int height; cell (int r, int c, int h): row(r), col(c), height(h) {}};class compLess {public: bool operator () (const cell& a, const cell& b) { return a.height > b.height; }};class Solution {public: int trapRainWater(vector<vector<int>>& heightMap) { int nrow = heightMap.size(); if (nrow < 3) return 0; int ncol = heightMap[0].size(); if (ncol < 3) return 0; priority_queue<cell, vector<cell>, compLess> pq; for (int i = 0; i < nrow; i++) { for (int j = 0; j < ncol; j++) { if (i == 0 || i == nrow - 1 || j == 0 || j == ncol - 1) { cell temp = {i, j, heightMap[i][j]}; pq.push(temp); } } } vector<vector<int>> isVisited(nrow, vector<int>(ncol, 0)); vector<vector<int>> dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int res = 0; while (!pq.empty()) { auto top = pq.top(); pq.pop(); for (auto d : dir) { int r = top.row + d[0]; int c = top.col + d[1]; if (r > 0 && r < nrow - 1 && c > 0 && c < ncol - 1 && !isVisited[r][c]) { res += max(0, top.height - heightMap[r][c]); isVisited[r][c] = 1; pq.push({r, c, max(top.height, heightMap[r][c])}); } } } return res; }};
阅读全文
1 0
- 407. Trapping Rain Water II
- 407. Trapping Rain Water II
- 407. Trapping Rain Water II
- 407. Trapping Rain Water II
- 407. Trapping Rain Water II
- 407. Trapping Rain Water II
- Trapping Rain Water II
- Trapping Rain Water II
- Trapping Rain Water II
- Trapping Rain Water II
- Leetcode 407. Trapping Rain Water II
- LeetCode 407. Trapping Rain Water II
- [LeetCode]407. Trapping Rain Water II
- Leetcode 407. Trapping Rain Water II
- [leetcode]407. Trapping Rain Water II
- leetcode 407. Trapping Rain Water II
- leetcode 407. Trapping Rain Water II
- Leetcode 407. Trapping Rain Water II
- 先完成功能,再想原理?
- React学习笔记-注释
- linux 利用iptables 端口转发
- springboot02Spring Boot JPA/Hibernate/Spring Data
- 利用Windows部署服务通过网络,批量安装Windows 7旗舰版
- 407. Trapping Rain Water II
- python爬虫实战--selenium验证码保存+多线程多标签+自动点击+完整代码
- android 四种启动模式
- 谷歌发布了一款AI工具 可以帮助基因组数据解读 | 速递
- 欢迎使用CSDN-markdown编辑器
- poj3167
- 科学家发现让人类幸福感飙升的密码!给大脑植入这个算法 | 精选
- Unity 导出 Facebook GameRoom
- java.lang.ThreadLocal 深入理解