Leetcode 407. Trapping Rain Water Ⅱ

 

首先,将四条边上的点加入PQ中,且标记为visited

Repeat until PQ is empty:

     pop PQ中的最小值min,遍历它的四个邻居neighbor:

          如果neighbor没有被visited:

               result += max(0, min - neighbor)

               设置neighbor = max(neighbor, min),并加入PQ中,且标记为visited

class Solution {
public:
    typedef struct Info
    {
        int h;
        int i;
        int j;
        Info(int _h, int _i, int _j):h(_h), i(_i), j(_j){}
        bool operator<(const Info &b)const{return h>b.h;}
        bool operator>(const Info &b)const{return h<b.h;}
    }Vertex;
    
    
    int trapRainWater(vector<vector<int>>& heightMap) {
        int row = heightMap.size();
        if (row <= 2)
            return 0;
        int column = heightMap[0].size();
        if (column <= 2)
            return 0;
        
        vector<Vertex> pq;
        set<int> s;
        for (int i = 0; i < row; ++i) {
            pq.emplace_back(heightMap[i][0], i, 0);
            push_heap(pq.begin(), pq.end());
            s.insert(i*column);
            pq.emplace_back(heightMap[i][column-1], i, column - 1);
            push_heap(pq.begin(), pq.end());
            s.insert(i*column + column - 1);
        }
        for (int j = 1; j < column - 1; ++j) {
            pq.emplace_back(heightMap[0][j], 0, j);
            push_heap(pq.begin(), pq.end());
            s.insert(j);
            pq.emplace_back(heightMap[row-1][j], row-1, j);
            push_heap(pq.begin(), pq.end());
            s.insert((row - 1) * column + j);
        }
        
        int result = 0;
        while (pq.size() > 0) {
            pop_heap(pq.begin(), pq.end());
            Vertex v = pq.back();
            int h = v.h, i = v.i, j = v.j;
            pq.pop_back();
            vector<vector<int>> neighbors = {{i+1,j},
                                             {i-1,j},
                                             {i,j+1},
                                             {i,j-1}};
            for (auto n : neighbors){
                if (n[0] < 0 || n[0] >= row || n[1] < 0 || n[1] >= column)
                    continue;
                int key = n[0] * column + n[1];
                auto iter = s.find(key);
                if (iter != s.end())
                    continue;
                s.insert(key);
                result += max(0, h - heightMap[n[0]][n[1]]);
                pq.emplace_back(max(h, heightMap[n[0]][n[1]]), n[0], n[1]);
                push_heap(pq.begin(), pq.end());
            }
        }
        return result;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值