算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 接雨水 II,我们先来看题面:
https://leetcode-cn.com/problems/trapping-rain-water-ii/
Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining.
给你一个 m x n 的矩阵,其中的值均为非负整数,代表二维高度图每个单元的高度,请计算图中形状最多能接多少体积的雨水。
示例
解题
https://blog.youkuaiyun.com/weixin_42054167/article/details/91989108
此题用BFS来做。创建一个优先级队列,该队列中是将高度小的放在队首。先将四周一圈的格子加入队列中,并将这些格子的状态设为已访问过。下面开始BFS,从队列的头部取出元素,并用其高度更新海平面level,然后从该格子向四周寻找格子,如果某格子未被访问过,那么将其状态设为已访问过,然后判断如果其高度小于海平面,那么把它们的高度差加到ans中,否则不操作。接下来将该格子加入到优先级队列中。如此进行,当优先级队列为空时退出循环,返回ans。
struct Node{
int i,j,h;
Node(int ii,int jj,int hh):i(ii),j(jj),h(hh){}
bool operator <(const Node &root) const{
return h>root.h;
}
};
class Solution {
public:
int trapRainWater(vector<vector<int>>& heightMap) {
if(heightMap.size()==0) return 0;
int m=heightMap.size(),n=heightMap[0].size(),area=0,h=0;
priority_queue<Node> q;
vector<vector<bool>> visit(m,vector<bool>(n,false));
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(i==0||i==m-1||j==0||j==n-1){
q.push(Node(i,j,heightMap[i][j]));
visit[i][j]=true;
}
}
}
vector<int> x={0,0,-1,1},y={-1,1,0,0};
while(!q.empty())
{
auto f=q.top();
if(h<f.h) h++;
else
{
q.pop();
for(int k=0;k<4;k++)
{
int i=f.i+x[k],j=f.j+y[k];
if(i>=0&&i<m&&j>=0&&j<n&&visit[i][j]==false)
{
int hh=heightMap[i][j];
if(hh<h) area+=h-hh;
q.push(Node(i,j,hh));
visit[i][j]=true;
}
}
}
}
return area;
}
};
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: