20190427-Leetcode-407.接雨水2

Leetcode-407.接雨水2

给定一个 m x n 的矩阵,其中的值均为正整数,代表二维高度图每个单元的高度,请计算图中形状最多能接多少体积的雨水。
说明:
m 和 n 都是小于110的整数。每一个单位的高度都大于0 且小于 20000。
示例:
给出如下 3x6 的高度图:
[
[1,4,3,1,3,2],
[3,2,1,3,2,4],
[2,3,3,2,3,1]
]
返回 4。

思路
从外圈最低的点开始遍历其内部的点
算法思路
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

代码

class Solution {
public:
    struct Qitem{
        int x;
        int y;
        int h;
        Qitem(int x, int y, int h): x(x), y(y), h(h){}
    };
    struct cmp{
        bool operator()(const Qitem &a, const Qitem &b){
            return a.h > b.h;
        }
    };
    int trapRainWater(vector<vector<int>>& heightMap) {
        priority_queue<Qitem, vector<Qitem>, cmp> Q;
        if(heightMap.size() < 3 || heightMap[0].size() < 3){
            return 0;
        }
        int row = heightMap.size();
        int col = heightMap[0].size();
        vector<vector<int> > mark;
        for(int i = 0; i < row; i++){
            mark.push_back(vector<int>(col, 0));
        }
        
        for(int i = 0; i < row; i++){
            Q.push(Qitem(i, 0, heightMap[i][0]));
            mark[i][0] = 1;
            Q.push(Qitem(i, col - 1, heightMap[i][col - 1]));
            mark[i][col - 1] = 1;
        }
        for(int i = 1; i < col - 1; i++){
            Q.push(Qitem(0, i, heightMap[0][i]));
            mark[0][i] = 1;
            Q.push(Qitem(row - 1, i, heightMap[row - 1][i]));
            mark[row - 1][i] = 1;
        }
        
        const int dx[] = {-1, 1, 0, 0};
        const int dy[] = {0, 0, -1, 1};
        int result = 0;
        while(!Q.empty()){
            int x = Q.top().x;
            int y = Q.top().y;
            int h = Q.top().h;
            Q.pop();
            for(int i = 0; i < 4; i++){
                int newx = x + dx[i];
                int newy = y + dy[i];
                if(newx < 0 || newx >= row || newy < 0 || newy >= col || mark[newx][newy]){
                    continue;
                }
                if(heightMap[newx][newy] < h){
                    result += h - heightMap[newx][newy];
                    heightMap[newx][newy] = h;
                }
                Q.push(Qitem(newx, newy, heightMap[newx][newy]));
                mark[newx][newy] = 1;
            }
        }
        return result;
    }
};
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值