码迷,mamicode.com
首页 > 移动开发 > 详细

407. Trapping Rain Water II

时间:2017-03-09 19:47:13      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:int   leetcode   following   matrix   height   pre   volume   note   cto   

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;
    }
};

 

407. Trapping Rain Water II

标签:int   leetcode   following   matrix   height   pre   volume   note   cto   

原文地址:http://www.cnblogs.com/tsunami-lj/p/6527199.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!