407. Trapping Rain Water II

本文介绍了一种计算二维高度地图中雨水可积累体积的算法。通过使用优先队列存储边界点,并利用最小堆每次从边界上的最小值出发,计算其相邻点的水位高度,从而得出整体的积水体积。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining.

Note:
Both m and n are less than 110. The height of each unit cell is greater than 0 and is less than 20,000.

Example:

Given the following 3x6 height map:
[
  [1,4,3,1,3,2],
  [3,2,1,3,2,4],
  [2,3,3,2,3,1]
]

Return 4.

这题有点难,一开始打算沿用上一题的思路,找到每个方向上的最大值坐标,根据每个点再最大值上或者下,左或者右,来分析这个点应该被上下左右四个邻居中的哪两个控制增长进水量。后来发现这种条件下改变的状态不具有决定性,周围状态的改变会对这个点的状态继续产生影响,这种思路作罢。
如何计算出具有决定性的状态?这题的讨论区给出了很好的做法,用priority_queue来储存border的所有点,用minheap,这样每次都从边界上的最小值出发,它对它的相邻的点都有决定意义。然后依次扩散,每次都从最小点开始计算。因为这些点的值都不应该再变了,所以他们扩散的影响具有决定意义。

代码:

class cell {
public:
    int row;
    int col;
    int height;
    cell (int r, int c, int h): row(r), col(c), height(h) {}
};
class compLess {
public:
    bool operator () (const cell& a, const cell& b) {
        return a.height > b.height;
    }

};
class Solution {
public:
    int trapRainWater(vector<vector<int>>& heightMap) {
        int nrow = heightMap.size();
        if (nrow < 3) return 0;
        int ncol = heightMap[0].size();
        if (ncol < 3) return 0;

        priority_queue<cell, vector<cell>, compLess> pq;

        for (int i = 0; i < nrow; i++) {
            for (int j = 0; j < ncol; j++) {
                if (i == 0 || i == nrow - 1 || j == 0 || j == ncol - 1) {
                    cell temp = {i, j, heightMap[i][j]};
                    pq.push(temp);
                }
            }
        }

        vector<vector<int>> isVisited(nrow, vector<int>(ncol, 0));
        vector<vector<int>> dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        int res = 0;
        while (!pq.empty()) {
            auto top = pq.top();
            pq.pop();
            for (auto d : dir) {
                int r = top.row + d[0];
                int c = top.col + d[1];
                if (r > 0 && r < nrow - 1 && c > 0 && c < ncol - 1 && !isVisited[r][c]) {
                    res += max(0, top.height - heightMap[r][c]);
                    isVisited[r][c] = 1;
                    pq.push({r, c, max(top.height, heightMap[r][c])});
                } 
            }
        }


        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值