407. 接雨水 II

给你一个 m x n 的矩阵,其中的值均为非负整数,代表二维高度图每个单元的高度,请计算图中形状最多能接多少体积的雨水。

示例 1:

输入: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
输出: 4
解释: 下雨后,雨水将会被上图蓝色的方块中。总的接雨水量为1+2+1=4。

示例 2:

输入: heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]
输出: 10

提示:

  • m == heightMap.length
  • n == heightMap[i].length
  • 1 <= m, n <= 200
  • 0 <= heightMap[i][j] <= 2 * 104

int trapRainWater(vector<vector<int>>& heightMap)
{
    //1.把外围的点放到优先队列,优先队列把最小优先出队
    //2.每天点都要四个方面都要访问

    typedef pair<int, int> qp;
    priority_queue<qp, vector<qp>, greater<qp> >que;//从小到大排序
    vector<int> direction = { -1,0,1,0,-1 };//左、上、右、下

    int row = heightMap.size();
    int col = heightMap[0].size();
    vector<vector<bool>>visitedVec(row, vector<bool>(col, false));
    

    //
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
        {
            if (true == visitedVec[i][j])
            {
                continue;
            }
            if (i == 0 || i == row - 1 || j == 0 || j == col - 1)//外围点保存
            {
                que.push(qp{ heightMap[i][j],i*col + j });
                visitedVec[i][j] = true;
            }
        }
    }

    int result = 0;
    while (!que.empty())
    {
        qp top =que.top();
        que.pop();
        int nx = top.second / col;
        int ny = top.second % col;
        for (int k = 0; k < 4; k++)
        {
            int x = nx+direction[k];
            int y = ny+direction[k + 1];
            if (x == 0 || x == row - 1 || y == 0 || y == col - 1)//外围
            {
                continue;
            }
            if (x<0 || x> row - 1 || y<0 || y>col - 1)//超出范围
            {
                continue;
            }
            if (visitedVec[x][y] == true)
            {
                continue;
            }
            if (heightMap[x][y]>top.first)
            {
                que.push(qp{ heightMap[x][y],x*col + y });
                visitedVec[x][y] = true;
            }
            else
            {
                result += top.first - heightMap[x][y];
                heightMap[x][y] = top.first;
                que.push(qp{ heightMap[x][y],x*col + y });
                visitedVec[x][y] = true;
            }
        }
    }
    return result;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值