Topic:
Given n * m non-negative integers representing an elevation map 2d where the area of each cell was 1 * 1, compute how much Water it is able to trap after raining.
Ideas:
This problem is an extension of the previous question, http://www.cnblogs.com/AndyJee/p/4821590.html
The previous given is a one-dimensional array, and here is a two-dimensional array, the image of understanding, is to provide a three-dimensional cylindrical container, to find the maximum size of the container can accommodate.
As the water is flowing to the low, so for this kind of trapping water problem, we only use from the outermost layer to the inside to connect the rainwater.
First find the smallest column from the outermost layer of the matrix, can be implemented by the heap, when the heap is not empty, each pop is the height of the smallest column, at this time from the pillar, traversing its surrounding four direction (BSF) pillars, if a pillar has not reached or exceeded the boundary and has not been accessed, The column is added to the heap, and if the height of the column is smaller than the current column height, the height of the column is updated, and the water contained here is recorded until the heap is empty.
Code:
#include <iostream>#include<vector>#include<stdlib.h>#include<queue>using namespacestd;structcell{intx; inty; inth; Cell (intXxintYyinthh): X (xx), Y (yy), H (HH) {}; BOOL operator< (ConstCell &c)Const{ returnH>c.h; }};/*bool operator< (const cell &a,const cell &b) {return a.h>b.h;}*/intTraprainwater (Constvector<vector<int> > &Heights) { intm=heights.size (); intn=heights[0].size (); Vector<vector<int> > Visited (m,vector<int> (n,0)); intdx[]={1,-1,0,0}; intdy[]={0,0,1,-1}; Priority_queue<cell>PQ; for(intI=0; i<n;i++) {Pq.push (cell (0, i,heights[0][i])); Pq.push (cell (M-1, i,heights[m-1][i])); visited[0][i]=1; Visited[m-1][i]=1; } for(intI=0; i<m;i++) {Pq.push (cell (i,0, heights[i][0])); Pq.push (cell (I,n-1, heights[i][n-1])); visited[i][0]=1; Visited[i][n-1]=1; } intans=0; while(!Pq.empty ()) {Cell C=Pq.top (); Pq.pop (); for(intI=0;i<4; i++){ for(intj=0;j<4; j + +){ intnextx=c.x+Dx[i]; intnexty=c.y+Dy[i]; if(nextx>=0&& nextx<m && nexty>=0&& nexty<n && visited[nextx][nexty]==0) {Visited[nextx][nexty]=1; intH=Max (c.h,heights[nextx][nexty]); Pq.push (cell (nextx,nexty,h)); Ans+=max (0, c.h-Heights[nextx][nexty]); } } } } returnans;}intmain () {vector<vector<int> > heights={ { A, -,0, A}, { -,4, -, A}, { -,8,Ten, A}, { A, -, A, A}, { -, -, -, -} }; cout<< Traprainwater (Heights) <<endl;//ans=14 return 0;}
(algorithm) trapping Rain water II