No.50 - leetCode407- 二维蓄水-边界水面上升-很难

本文介绍了一种高效的算法,用于解决雨水陷阱问题。通过模拟水面上升的过程,算法从边界开始逐步渗透到内部单元,将成功的渗透单元转化为新的边界,直至整个地图被覆盖。此方法避免了DFS搜索可能遇到的复杂情况和反例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

尝试过DFS搜索最小边界写这道题,很麻烦,总有反例。


正手应该是模拟水面上升,比较容易懂。

随着水面上升,
从边界一点点往内部渗透,
当成功渗透内部单元后,
内部单元成为新的边界。

class Solution {
public:
 
struct Node{
    int h;
    int x;
    int y;
    Node(int a,int b,int c):h(a),x(b),y(c){};
    bool operator < (const Node a) const{
        if(a.h < this->h) return true;
        return false;
    }
};

int trapRainWater(vector<vector<int>>& heightMap) {
    int R = heightMap.size();
    if( R <= 2) return 0;
    int C = heightMap[0].size();
    if( C <= 2) return 0;
    priority_queue<Node,vector<Node>> q;  
    vector<vector<int>> v(R,vector<int>(C,0));
    const int dirx[] = {-1,0,1,0};
    const int diry[] = {0,1,0,-1};  
    for(int i=0;i<R;i++){
        q.push(*(new Node(heightMap[i][0],i,0)));
        q.push(*(new Node(heightMap[i][C-1],i,C-1)));
        v[i][0] = v[i][C-1] = 1;
    }
    for(int j=0;j<C;j++){
        q.push(*(new Node(heightMap[0][j],0,j)));
        q.push(*(new Node(heightMap[R-1][j],R-1,j)));
        v[0][j] = v[R-1][j] = 1;
    }
    int mWall = 0;
    int ans = 0;
    while(!q.empty()){
        int h = q.top().h;
        int x = q.top().x;
        int y = q.top().y;
        q.pop();
        mWall = max(mWall,h);
        for(int i=0;i<4;i++){
            int r = x + dirx[i];
            int c = y + diry[i];
            if(r < 1 || r >= R-1 || c < 1 || c >= C-1 || v[r][c]) continue;
            v[r][c] = 1;
            if(heightMap[r][c] < mWall){
                ans += mWall - heightMap[r][c];
                heightMap[r][c] = mWall;
            }
            q.push(*(new Node(heightMap[r][c],r,c)));
        }
    }
    return ans;
}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值