题目描述:
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.
The above image represents the elevation map [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] before the rain.
After the rain, water are trapped between the blocks. The total volume of water trapped is 4.
算法分析:
参考解题步骤视频
大概思路是取最外层的地板加入优先队列,不断让高度最低的地板出队,用其高度更新max,并继续将外层地板加入队列,加入之前累加其与max的高度差(若大于max)
代码:
class Solution {
private:
struct cell {
int x,y;
int height;
cell (int a, int b, int h):x(a), y(b), height(h) {}
bool operator < (const cell &a) const {
return this->height > a.height;
}
};
public:
int trapRainWater(vector<vector<int>>& heightMap) {
if (heightMap.size() == 0) return 0;
int r = heightMap.size();
int c = heightMap[0].size();
vector< vector<bool> > flags(r, vector<bool>(c, 0));
priority_queue<cell> que;
for (int i = 0; i < r; i++) {
que.push(cell(i, 0, heightMap[i][0]));
que.push(cell(i, c-1, heightMap[i][c-1]));
flags[i][0] = flags[i][c-1] = true;
}
for (int i = 1; i < c-1; i++) {
que.push(cell(0, i, heightMap[0][i]));
que.push(cell(r-1, i, heightMap[r-1][i]));
flags[0][i] = flags[r-1][i] = true;
}
int max = 0;
cell tmp(0,0,0);
int count = 0;
while (!que.empty()) {
tmp = que.top();
que.pop();
if (tmp.height > max) max = tmp.height;
if (tmp.x > 0 && flags[tmp.x-1][tmp.y] == false) {
que.push(cell(tmp.x-1, tmp.y, heightMap[tmp.x-1][tmp.y]));
flags[tmp.x-1][tmp.y] = true;
count += (max > heightMap[tmp.x-1][tmp.y]) ? (max-heightMap[tmp.x-1][tmp.y]) : 0;
}
if (tmp.y > 0 && flags[tmp.x][tmp.y-1] == false) {
que.push(cell(tmp.x, tmp.y-1, heightMap[tmp.x][tmp.y-1]));
flags[tmp.x][tmp.y-1] = true;
count += (max > heightMap[tmp.x][tmp.y-1]) ? (max-heightMap[tmp.x][tmp.y-1]) : 0;
}
if (tmp.x < r-1 && flags[tmp.x+1][tmp.y] == false) {
que.push(cell(tmp.x+1, tmp.y, heightMap[tmp.x+1][tmp.y]));
flags[tmp.x+1][tmp.y] = true;
count += (max > heightMap[tmp.x+1][tmp.y]) ? (max-heightMap[tmp.x+1][tmp.y]) : 0;
}
if (tmp.y < c-1 && flags[tmp.x][tmp.y+1] == false) {
que.push(cell(tmp.x, tmp.y+1, heightMap[tmp.x][tmp.y+1]));
flags[tmp.x][tmp.y+1] = true;
count += (max > heightMap[tmp.x][tmp.y+1]) ? (max-heightMap[tmp.x][tmp.y+1]) : 0;
}
}
return count;
}
};
提交结果:
40 / 40 test cases passed.
Status: Accepted
Runtime: 19 ms
Your runtime beats 74.76 % of cpp submissions.