题目描述:给你一个 m x n
的矩阵,其中的值均为非负整数,代表二维高度图每个单元的高度,请计算图中形状最多能接多少体积的雨水。(难度:困难)
原题链接:407. 接雨水 II - 力扣(LeetCode) (leetcode-cn.com)
最短路算法
首先,最外面一层,外面是没有方块的,是无法接水的,与最外一层相邻方块,也被最外一层的“影响”,和“短板效应”的思想有点相似,因此我们可以利用最外一层作为突破口,然后往里面找。
我们可以用最短路算法DijkstraDijkstra算法解决该问题,DijkstraDijkstra利用堆(优先队列)维护了一个有序结构,每次拿出最短的边,我们可以利用最短路思想,把边迁移为“方块的高度”,进而解决我们这个问题。
设方块 (i,j)(i,j) 的最终的高度为 h[i][j]h[i][j],那么 h[i][j] = max(heightMap[i][j], min(h[i-1][j], h[i+1][j], h[i][j-1], h[i][j +1]))h[i][j]=max(heightMap[i][j],min(h[i−1][j],h[i+1][j],h[i][j−1],h[i][j+1]))。
最短路找的过程有几个注意点:
优先从矮的的方块开始找,一个格子周围有四个方块,但最终的盛水量,取决于最矮一个。
计算完当前方块盛水量,要更新当前点的高度,h[i][j] = max(heightMap[i][j], min(h[i-1][j], h[i+1][j], h[i][j-1], h[i][j +1]))h[i][j]=max(heightMap[i][j],min(h[i−1][j],h[i+1][j],h[i][j−1],h[i][j+1]))。
C++代码:
typedef pair<int,int> pii;
class Solution {
public:
int trapRainWater(vector<vector<int>>& heightMap) {
if (heightMap.size() <= 2 || heightMap[0].size() <= 2) {
return 0;
}
int m = heightMap.size();
int n = heightMap[0].size();
priority_queue<pii, vector<pii>, greater<pii>> pq;
vector<vector<bool>> visit(m, vector<bool>(n, false));
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) {
pq.push({heightMap[i][j], i * n + j});
visit[i][j] = true;
}
}
}
int res = 0;
int dirs[] = {-1, 0, 1, 0, -1};
while (!pq.empty()) {
pii curr = pq.top();
pq.pop();
for (int k = 0; k < 4; ++k) {
int nx = curr.second / n + dirs[k];
int ny = curr.second % n + dirs[k + 1];
if( nx >= 0 && nx < m && ny >= 0 && ny < n && !visit[nx][ny]) {
if (heightMap[nx][ny] < curr.first) {
res += curr.first - heightMap[nx][ny];
}
visit[nx][ny] = true;
pq.push({max(heightMap[nx][ny], curr.first), nx * n + ny});
}
}
}
return res;
}
};