Trapping Rain Water II
来源:互联网 发布:win10更改Mac 编辑:程序博客网 时间:2024/06/05 11:26
维护一个最小堆,保存最外围的高度
每次取堆中最小高度 h,查看周围4个没有被访问过的元素:
如果某个周围元素的高度小于 h,则注入水到其中,并将其加入到最小堆中,设置该元素被访问过,记录注水的量,即增加ans
每次取堆中最小高度 h,查看周围4个没有被访问过的元素:
如果某个周围元素的高度小于 h,则注入水到其中,并将其加入到最小堆中,设置该元素被访问过,记录注水的量,即增加ans
如果某个周围元素的高度大于 h,则直接将其加入到最小堆中,设置改元素被访问过
class Solution {public:struct Node {int x, y, h;Node(int xx, int yy, int hh) : x(xx), y(yy), h(hh) {}friend bool operator < (const Node &n1, const Node &n2) { return n1.h > n2.h; }};int trapRainWater(vector<vector<int>>& heightMap) {int W, H, ans = 0;H = heightMap.size();W = heightMap[0].size();vector<vector<bool> > visited(H, vector<bool>(W, false));priority_queue<Node, vector<Node>,less<Node>> pq;for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) {if (i == 0 || i == H - 1 || j == 0 || j == W - 1) {Node n(i, j, heightMap[i][j]);pq.push(n);visited[i][j] = true;}}int dir[4][2] = { { -1,0 },{ 0,-1 },{ 1,0 },{ 0,1 } };while (!pq.empty()) {Node top = pq.top(); pq.pop();for (int d = 0; d < 4; d++) {int next_x = top.x + dir[d][0], next_y = top.y + dir[d][1];if (next_x < 0 || next_y < 0 || next_x >= H || next_y >= W) continue;if (visited[next_x][next_y]) continue;visited[next_x][next_y] = true;Node tmp(next_x, next_y, heightMap[next_x][next_y]);if (tmp.h < top.h) {ans += top.h - tmp.h;tmp.h = top.h;}pq.push(tmp);}}return ans;}};
0 0
- Trapping Rain Water II
- Trapping Rain Water II
- Trapping Rain Water II
- 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
- Leetcode407. Trapping Rain Water II
- 407. Trapping Rain Water II
- N-Queens I,II, Trapping Rain Water
- LintCode 364 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
- R语言连接Oracle的一种方式:使用ROacle
- 用runtime给textView添加placeholder
- [iOS Xcode8]上传AppStore 无法构建版本 没有➕号
- 深度学习常用链接
- API 23 widget.RelativeLayout——属性分析
- Trapping Rain Water II
- 《嫌疑人X的替身》扑朔迷离的剧情
- 基于大数据分析的安全管理平台技术研究及应用
- 【.Net码农】【NPOI】NPOI对Excel的操作(Sheet转DataTable、List<T>)
- Standard 1.1.x VM与Standard VM的区别
- 从caffe中新增layer(cpp版本)
- 2000: [Hnoi2010]stone 取石头游戏 关于题目数据有质疑
- linux中的文件和文件夹的新建、查询、删除
- c语言小知识点