题意:
给你一个 m x n 的矩阵,其中的值均为非负整数,代表二维高度图每个单元的高度,请计算图中形状最多能接多少体积的雨水。
思路:
跟接雨水Ⅰ里短板原理一样,对于每个点能接水的体积,现在取决于他四周接完水之后的高度了,即当前位置能接水的体积等于相邻四周最低的那个,我们维护一个最小堆,每次从堆里取出接水后高度最低的那个来,用它来更新他四周接完水后的高度即可
public int trapRainWater(int[][] heightMap) {
int n=heightMap.length;
int m=heightMap[0].length;
if(n<=2||m<=2){
return 0;
}
PriorityQueue<int []> priorityQueue=new PriorityQueue<>((o1,o2)-> o1[1]-o2[1]);
boolean book[][]=new boolean[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(i==0||i==n-1||j==0||j==m-1){
priorityQueue.add(new int[]{i*m+j,heightMap[i][j]});
book[i][j]=true;
}
}
}
int mov[][]=new int[][]{{1,0},{0,1},{-1,0},{0,-1}};
int ans=0;
while(!priorityQueue.isEmpty()){
int now[]=priorityQueue.poll();
int x=now[0]/m;
int y=now[0]%m;
for(int i=0;i<4;i++){
int nowx=x+mov[i][0];
int nowy=y+mov[i][1];
if(nowx>=0&&nowx<n&&nowy>=0&&nowy<m&&!book[nowx][nowy]){
priorityQueue.add(new int[]{nowx*m+nowy,Math.max(heightMap[nowx][nowy],now[1])});
book[nowx][nowy]=true;
if(now[1]>heightMap[nowx][nowy]){
ans+=now[1]-heightMap[nowx][nowy];
}
}
}
}
return ans;
}
时间复杂度 O(MNlog(M+N))
空间复杂度 O(MN)