trapping Rain Water II
Given n x m non-negative integers representing an elevation map 2d where the area of each cell is 1< /c3> x 1, compute how much water it's able to trap after raining.
Example
Given 5*4 Matrix
[12,13,0,12][13,4,13,12][13,8,10,12][12,13,12,12][13,13,13,13]
Return 14 .
Tags Expand
Lintcode Copyright Heap Matrix
Minimize the heap. Note that when you put new elements into the heap, you need to update the height of the position at the same time. That
Heap.emplace (xx, yy, Max (U.h, Heights[xx][yy]));
Also note that the priority queue defaults to the large top heap, which uses the < number by default, so if you want to use a small top heap, you want to return a > B when you write the CMP functor, not a < B.
1 classSolution {2 Public:3 /**4 * @param heights:a matrix of integers5 * @return: An integer6 */7 structCell {8 intx, y;9 inth;Ten cell () {} OneCellint_x,int_y,int_h): X (_x), Y (_y), H (_h) {} A }; - structCMP { - BOOL operator() (ConstCell &a,ConstCell &b) { the returnA.h >b.h; - } - }; - intTraprainwater (vector<vector<int> > &Heights) { + //Write your code here - if(Heights.empty () | | heights[0].empty ())return 0; + intn = heights.size (), M = heights[0].size (); Avector<vector<BOOL>> visit (N, vector<BOOL> (M,false)); atPriority_queue<cell, Vector<cell>, cmp>Heap; - for(inti =0; I < n; ++i) { -Heap.emplace (I,0, heights[i][0]); -Heap.emplace (i, M-1, heights[i][m-1]); -visit[i][0] = visit[i][m-1] =true; - } in for(intj =0; J < M; ++j) { -Heap.emplace (0, J, heights[0][j]); toHeap.emplace (N-1, J, heights[n-1][j]); +visit[0][J] = visit[n-1][J] =true; - } the intres =0; * Const intdx[4] = {0,1,0, -1}; $ Const intdy[4] = {1,0, -1,0};Panax Notoginseng while(!Heap.empty ()) { -Auto U =heap.top (); the Heap.pop (); + for(inti =0; I <4; ++i) { A intxx = u.x + dx[i], yy = U.y +Dy[i]; the if(XX >=0&& xx < n && yy >=0&& yy < M &&!Visit[xx][yy]) { +Res + = max (0, U.h-Heights[xx][yy]); - heap.emplace (xx, yy, Max (U.h, Heights[xx][yy])); $VISIT[XX][YY] =true; $ } - } - } the returnRes; - }Wuyi};
[Lintcode] Trapping Rain Water II