Trapping Rain Water II

来源:互联网 发布:win10更改Mac 编辑:程序博客网 时间:2024/06/05 11:26
维护一个最小堆,保存最外围的高度
每次取堆中最小高度 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
原创粉丝点击