structT{inti;intj;inth;// heightMap[i][j] or the height after filling waterT(inti,intj,inth):i(i),j(j),h(h){}};classSolution{public:inttrapRainWater(vector<vector<int>>&heightMap){constintm=heightMap.size();constintn=heightMap[0].size();constvector<int>dirs{0,1,0,-1,0};intans=0;autocompare=[](constT&a,constT&b){returna.h>b.h;};priority_queue<T,vector<T>,decltype(compare)>minHeap(compare);vector<vector<bool>>seen(m,vector<bool>(n));for(inti=0;i<m;++i){minHeap.emplace(i,0,heightMap[i][0]);minHeap.emplace(i,n-1,heightMap[i][n-1]);seen[i][0]=true;seen[i][n-1]=true;}for(intj=1;j<n-1;++j){minHeap.emplace(0,j,heightMap[0][j]);minHeap.emplace(m-1,j,heightMap[m-1][j]);seen[0][j]=true;seen[m-1][j]=true;}while(!minHeap.empty()){constauto[i,j,h]=minHeap.top();minHeap.pop();for(intk=0;k<4;++k){constintx=i+dirs[k];constinty=j+dirs[k+1];if(x<0||x==m||y<0||y==n)continue;if(seen[x][y])continue;if(heightMap[x][y]<h){ans+=h-heightMap[x][y];minHeap.emplace(x,y,h);// Fill the water on grid[x][y]}else{minHeap.emplace(x,y,heightMap[x][y]);}seen[x][y]=true;}}returnans;}};
classT{publicinti;publicintj;publicinth;// heightMap[i][j] or the height after filling waterpublicT(inti,intj,inth){this.i=i;this.j=j;this.h=h;}}classSolution{publicinttrapRainWater(int[][]heightMap){finalintm=heightMap.length;finalintn=heightMap[0].length;finalint[]dirs={0,1,0,-1,0};intans=0;Queue<T>minHeap=newPriorityQueue<>((a,b)->a.h-b.h);boolean[][]seen=newboolean[m][n];for(inti=0;i<m;++i){minHeap.offer(newT(i,0,heightMap[i][0]));minHeap.offer(newT(i,n-1,heightMap[i][n-1]));seen[i][0]=true;seen[i][n-1]=true;}for(intj=1;j<n-1;++j){minHeap.offer(newT(0,j,heightMap[0][j]));minHeap.offer(newT(m-1,j,heightMap[m-1][j]));seen[0][j]=true;seen[m-1][j]=true;}while(!minHeap.isEmpty()){finalinti=minHeap.peek().i;finalintj=minHeap.peek().j;finalinth=minHeap.poll().h;for(intk=0;k<4;++k){finalintx=i+dirs[k];finalinty=j+dirs[k+1];if(x<0||x==m||y<0||y==n)continue;if(seen[x][y])continue;if(heightMap[x][y]<h){ans+=h-heightMap[x][y];minHeap.offer(newT(x,y,h));// Fill the water on grid[x][y]}else{minHeap.offer(newT(x,y,heightMap[x][y]));}seen[x][y]=true;}}returnans;}}