• 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>& heightMap)
    {
        //1.把外围的点放到优先队列,优先队列把最小优先出队
        //2.每天点都要四个方面都要访问

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

        int row = heightMap.size();
        int col = heightMap[0].size();
        vector>visitedVec(row, vector(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;

    }

     

  • 相关阅读:
    flex布局方法学习
    (二) MdbCluster分布式内存数据库——分布式架构
    数据链路层-可靠传输实现机制(回退N帧协议GBN)
    C++编程 零矩阵详解
    【英语:基础进阶_核心词汇扩充】E2.常见词后缀拓词
    Java NIO
    Hadoop3教程(七):MapReduce概述
    【教学类-14-01】20221113《图形数量统计6*6-2》(大班主题《》)
    FGF21 类似物 PF-05231023 改善糖尿病并发症
    输入年月日判断是本年的第多少天
  • 原文地址:https://blog.csdn.net/yinhua405/article/details/128196245