leedcode 407. 接雨水2


思路分析 :
在二维中的接雨水,对每一个位置可以接水的量是其左侧的最大值和右侧的最大值中取小值
而在三维的接雨水中,首先可以知道的是最外面一层是不能接水的,因此对内层某一个位置的可以接水量,即为其四周高度的最小值决定的
我们可以借助优先队列,上来先将四周放入其中,取四周中最小的那个拿出来更新其邻域,新更新的再重新作为边界。
代码示例:
class Solution {
public:
struct node{
int x, y;
int h;
node(int _x, int _y, int _h): x(_x), y(_y), h(_h){}
bool operator< (const node &v) const{
return h > v.h;
}
};
int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
int trapRainWater(vector<vector<int>>& heightMap) {
priority_queue<node> que;
int m = heightMap.size();
int n = heightMap[0].size();
int vis[205][205];
memset(vis, 0, sizeof(vis));
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if (i == 0 || i == m-1 || j == 0 || j == n-1) {
que.push({i, j, heightMap[i][j]});
vis[i][j] = 1;
}
}
}
int ans = 0;
while(!que.empty()){
node v = que.top();
que.pop();
for(int i = 0; i < 4; i++){
int fx = v.x + dir[i][0];
int fy = v.y + dir[i][1];
if (fx >= 0 && fx < m && fy >= 0 && fy < n && !vis[fx][fy]){
if (heightMap[fx][fy] < v.h) {
ans += v.h - heightMap[fx][fy];
// heightMap[fx][fy] = v.h;
}
vis[fx][fy] = 1;
que.push({fx, fy, max(v.h, heightMap[fx][fy])});
}
}
}
return ans;
}
};
东北日出西边雨 道是无情却有情

浙公网安备 33010602011771号