前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Trapping Rain Water1,2 优先队列解法

Trapping Rain Water1,2 优先队列解法

作者头像
kalifa_lau
发布2018-08-03 11:16:21
3040
发布2018-08-03 11:16:21
举报
文章被收录于专栏:kalifaの日々
代码语言:javascript
复制
class Solution {
public:
    int trap(vector<int>& height) {
        pair<int,int> que;
        int len = height.size();
        if(len<3) return 0;
        int res = 0;
        que.first = 0;
        que.second = len-1;
        int Max = -1;
        while(que.first<que.second)
        {
            //Max = max(height[que.first],height[que.second]);
            if(height[que.first]<=height[que.second])
            {
                if(height[que.first]>Max) Max = height[que.first];
                if(Max>height[que.first+1]) res+=Max - height[que.first+1];
                que.first++;
            }
            else
            {
                if(Max<height[que.second]) Max = height[que.second];
                if(Max>height[que.second-1]) res+= Max-height[que.second-1];
                que.second--;
            }
            
        }
        return res;
    }
};
代码语言:javascript
复制
class Solution {
public:
    int trapRainWater(vector<vector<int>>& heightMap) {
        
        int res = 0;
        
        int m = heightMap.size();
        if(m==0) return 0;
        int n = heightMap[0].size();
        priority_queue < pair<int,pair<int,int>>,vector<pair<int,pair<int,int>>>,greater< pair<int,pair<int,int>> > > que;
        
        vector<vector<int> > visited(m,vector<int>(n,0));
        
        int dir[] = {0,1,0,-1,0};
        
        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)) continue;
                que.push(make_pair(heightMap[i][j],make_pair(i,j)));
                visited[i][j] = 1;
                
            }
        }

        int MAX = -10;
        while(!que.empty())
        {
            pair<int,pair<int,int>> temp = que.top();que.pop();
            if(temp.first>MAX) MAX = temp.first;
            
            int x = temp.second.first;
            int y = temp.second.second;
            
            
            
            for(int i=0;i<4;i++)
            {
                int a = x+dir[i];
                int b = y+dir[i+1];
                
                if(a>=0&&a<m&&b>=0&&b<n&&visited[a][b]==0)
                {
                    que.push(make_pair(heightMap[a][b],make_pair(a,b)));
                    if(MAX > heightMap[a][b])  res += MAX - heightMap[a][b];
                    visited[a][b] = 1;
                }
            }
        }
        return res;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.07.27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档