407. Trapping Rain Water II

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.

 


The above image represents the elevation map [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] before the rain.


After the rain, water are trapped between the blocks. The total volume of water trapped is 4.

解题思路:这题和"关门打狗"的想法是一样的,首先把最外面一圈围起来,利用一个优先队列每次从最矮的高度出发,往里面缩小范围,如果碰到更矮的,则此处可以积水当前高度-更矮的高度,如果碰到比自己高的,则把自己的高度变成高的高度,积水体积不变。

class Solution {
public:
    int trapRainWater(vector<vector<int>>& heightMap) {
        if(heightMap.empty())return 0;
        priority_queue<pair<int,int>, vector<pair<int,int> >, greater<pair<int,int> > >q;
        int n=heightMap.size(),m=heightMap[0].size();
        vector<vector<int> >vis(n,vector<int>(m,0));
        for(int i=0;i<n;i++){
            vis[i][0]=vis[i][m-1]=1;
            q.push(make_pair(heightMap[i][0],i*m));
            q.push(make_pair(heightMap[i][m-1],i*m+m-1));
        }
        for(int i=0;i<m;i++){
            vis[0][i]=vis[n-1][i]=1;
            q.push(make_pair(heightMap[0][i],i));
            q.push(make_pair(heightMap[n-1][i],(n-1)*m+i));
        }
        vector<vector<int> >dirs{{0,1},{1,0},{0,-1},{-1,0}};
        int res=0;
        while(!q.empty()){
            auto val=q.top();
            q.pop();
            int height=val.first,x=val.second/m,y=val.second%m;
            for(auto dir: dirs){
                int xx=x+dir[0],yy=y+dir[1];
                if(xx<0||xx>=n||yy<0||yy>=m||vis[xx][yy])continue;
                vis[xx][yy]=1;
                res += max(0,height-heightMap[xx][yy]);
                q.push(make_pair(heightMap[xx][yy],xx*m+yy));
            }
        }
        return res;
    }
};

 

posted @ 2017-03-09 18:58  Tsunami_lj  阅读(124)  评论(0编辑  收藏  举报