LeetCode 力扣C++题解 407. 接雨水 II

题目描述:给你一个 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;
    }
};

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值