[LintCode] Trapping rain water II

Given n x m non-negative integers representing an elevation map 2d where the area of each cell is 1 x 1, compute how much water it is 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.

struct MyPoint{
  int x, y, h;
  MyPoint(int xx, int yy, int hh):x(xx), y(yy), h(hh){}
};

struct Cmp{
  bool operator()(const MyPoint &p1, const MyPoint &p2){
      return p1.h > p2.h;
  }  
};

class Solution {
public:
    /**
     * @param heights: a matrix of integers
     * @return: an integer
     */
    int trapRainWater(vector<vector<int> > &heights) {
        int m = heights.size();
        if(m < 3) return 0;
        int n = heights[0].size();
        if(n < 3) return 0;
        
        int waterNum = 0;
        vector<vector<bool> > visit(m, vector<bool>(n, false));
        priority_queue<MyPoint, vector<MyPoint>, Cmp> MyPointQue;
        
        for(int i = 0;i < n;++i){
            MyPointQue.push(MyPoint(0, i, heights[0][i]));
            MyPointQue.push(MyPoint(m - 1, i, heights[m - 1][i]));
            visit[0][i] = true;
            visit[m - 1][i] = true;
        }
        
        for(int j = 1;j < m - 1;++j){
            MyPointQue.push(MyPoint(j, 0, heights[j][0]));
            MyPointQue.push(MyPoint(j, n - 1, heights[j][n - 1]));
            visit[j][0] = true;
            visit[j][n - 1] = true;
        }
        
        const int detX[] = {0, 0, 1, -1}, detY[] = {1, -1, 0, 0};
        while(MyPointQue.size() > 0){
            MyPoint p = MyPointQue.top();
            MyPointQue.pop();
            
            for(int i = 0;i < 4;++i){
                int xx = p.x + detX[i], yy = p.y + detY[i];
                if(xx < 0 || xx >= m || yy < 0 || yy >= n) continue;
                if(visit[xx][yy]) continue;
                else{
                    int h = heights[xx][yy];
                    if(heights[xx][yy] < p.h){
                        h = p.h;
                        waterNum += p.h - heights[xx][yy];
                    }
                    MyPointQue.push(MyPoint(xx, yy, h));
                    visit[xx][yy] = true;
                }
            }
        }
        return waterNum;
    }
};
原文地址:https://www.cnblogs.com/changchengxiao/p/4858563.html