Given m x n
a matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the VO Lume of water it is able to trap after raining.
Note:
Both m and N is less than 110. The height of each unit cell is greater than 0 and was less than 20,000.
Example:
Given the following 3x6 height map:[ [1,4,3,1,3,2], [3,2,1,3,2,4], [2,3,3,2,3,1]]return 4.
The above image represents the elevation map [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
before the rain.
After the rain, water is trapped between the blocks. The total volume of water trapped is 4.
Problem-solving ideas: This problem and "Alec" idea is the same, first the outermost circle around, the use of a priority queue each time from the shortest height, to narrow the scope, if you encounter a shorter, then here can be stagnant current height-higher height, if you encounter higher than yourself, then the height of their own heights into high , the volume of stagnant water is unchanged.
classSolution { Public: intTraprainwater (vector<vector<int>>&heightmap) { if(Heightmap.empty ())return 0; Priority_queue<pair<int,int, vector<pair<int,int>, greater<pair<int,int> > >Q; intN=heightmap.size (), m=heightmap[0].size (); Vector<vector<int> >vis (n,vector<int> (M,0)); for(intI=0; i<n;i++) {vis[i][0]=vis[i][m-1]=1; Q.push (Make_pair (heightmap[i][0],i*m)); Q.push (Make_pair (heightmap[i][m-1],i*m+m-1)); } for(intI=0; i<m;i++) {vis[0][i]=vis[n-1][i]=1; Q.push (Make_pair (heightmap[0][i],i)); Q.push (Make_pair (heightmap[n-1][i], (n1) *m+i)); } Vector<vector<int> >dirs{{0,1},{1,0},{0,-1},{-1,0}}; intres=0; while(!Q.empty ()) {Auto Val=Q.top (); Q.pop (); intheight=val.first,x=val.second/m,y=val.second%m; for(Auto dir:dirs) {intxx=x+dir[0],yy=y+dir[1]; if(xx<0|| xx>=n| | yy<0|| yy>=m| | VIS[XX][YY])Continue; VIS[XX][YY]=1; Res+ = Max (0, height-Heightmap[xx][yy]); Q.push (Make_pair (heightmap[xx][yy],xx*m+yy)); } } returnRes; }};
407. Trapping Rain Water II