407. Trapping Rain Water II

来源:互联网 发布:厦门博思软件 编辑:程序博客网 时间:2024/06/05 04:54

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;    }};
原创粉丝点击