首先,将四条边上的点加入PQ中,且标记为visited
Repeat until PQ is empty:
pop PQ中的最小值min,遍历它的四个邻居neighbor:
如果neighbor没有被visited:
result += max(0, min - neighbor)
设置neighbor = max(neighbor, min),并加入PQ中,且标记为visited
class Solution {
public:
typedef struct Info
{
int h;
int i;
int j;
Info(int _h, int _i, int _j):h(_h), i(_i), j(_j){}
bool operator<(const Info &b)const{return h>b.h;}
bool operator>(const Info &b)const{return h<b.h;}
}Vertex;
int trapRainWater(vector<vector<int>>& heightMap) {
int row = heightMap.size();
if (row <= 2)
return 0;
int column = heightMap[0].size();
if (column <= 2)
return 0;
vector<Vertex> pq;
set<int> s;
for (int i = 0; i < row; ++i) {
pq.emplace_back(heightMap[i][0], i, 0);
push_heap(pq.begin(), pq.end());
s.insert(i*column);
pq.emplace_back(heightMap[i][column-1], i, column - 1);
push_heap(pq.begin(), pq.end());
s.insert(i*column + column - 1);
}
for (int j = 1; j < column - 1; ++j) {
pq.emplace_back(heightMap[0][j], 0, j);
push_heap(pq.begin(), pq.end());
s.insert(j);
pq.emplace_back(heightMap[row-1][j], row-1, j);
push_heap(pq.begin(), pq.end());
s.insert((row - 1) * column + j);
}
int result = 0;
while (pq.size() > 0) {
pop_heap(pq.begin(), pq.end());
Vertex v = pq.back();
int h = v.h, i = v.i, j = v.j;
pq.pop_back();
vector<vector<int>> neighbors = {{i+1,j},
{i-1,j},
{i,j+1},
{i,j-1}};
for (auto n : neighbors){
if (n[0] < 0 || n[0] >= row || n[1] < 0 || n[1] >= column)
continue;
int key = n[0] * column + n[1];
auto iter = s.find(key);
if (iter != s.end())
continue;
s.insert(key);
result += max(0, h - heightMap[n[0]][n[1]]);
pq.emplace_back(max(h, heightMap[n[0]][n[1]]), n[0], n[1]);
push_heap(pq.begin(), pq.end());
}
}
return result;
}
};