Leetcode-407.接雨水2
给定一个 m x n 的矩阵,其中的值均为正整数,代表二维高度图每个单元的高度,请计算图中形状最多能接多少体积的雨水。
说明:
m 和 n 都是小于110的整数。每一个单位的高度都大于0 且小于 20000。
示例:
给出如下 3x6 的高度图:
[
[1,4,3,1,3,2],
[3,2,1,3,2,4],
[2,3,3,2,3,1]
]
返回 4。
思路:
从外圈最低的点开始遍历其内部的点
算法思路:
代码:
class Solution {
public:
struct Qitem{
int x;
int y;
int h;
Qitem(int x, int y, int h): x(x), y(y), h(h){}
};
struct cmp{
bool operator()(const Qitem &a, const Qitem &b){
return a.h > b.h;
}
};
int trapRainWater(vector<vector<int>>& heightMap) {
priority_queue<Qitem, vector<Qitem>, cmp> Q;
if(heightMap.size() < 3 || heightMap[0].size() < 3){
return 0;
}
int row = heightMap.size();
int col = heightMap[0].size();
vector<vector<int> > mark;
for(int i = 0; i < row; i++){
mark.push_back(vector<int>(col, 0));
}
for(int i = 0; i < row; i++){
Q.push(Qitem(i, 0, heightMap[i][0]));
mark[i][0] = 1;
Q.push(Qitem(i, col - 1, heightMap[i][col - 1]));
mark[i][col - 1] = 1;
}
for(int i = 1; i < col - 1; i++){
Q.push(Qitem(0, i, heightMap[0][i]));
mark[0][i] = 1;
Q.push(Qitem(row - 1, i, heightMap[row - 1][i]));
mark[row - 1][i] = 1;
}
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
int result = 0;
while(!Q.empty()){
int x = Q.top().x;
int y = Q.top().y;
int h = Q.top().h;
Q.pop();
for(int i = 0; i < 4; i++){
int newx = x + dx[i];
int newy = y + dy[i];
if(newx < 0 || newx >= row || newy < 0 || newy >= col || mark[newx][newy]){
continue;
}
if(heightMap[newx][newy] < h){
result += h - heightMap[newx][newy];
heightMap[newx][newy] = h;
}
Q.push(Qitem(newx, newy, heightMap[newx][newy]));
mark[newx][newy] = 1;
}
}
return result;
}
};