407. Trapping Rain Water II

来源:互联网 发布:易语言硬件断点源码 编辑:程序博客网 时间:2024/06/04 18:27

Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining.

Note:
Both m and n are less than 110. The height of each unit cell is greater than 0 and is 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 are trapped between the blocks. The total volume of water trapped is 4.


摘自

https://discuss.leetcode.com/topic/60418/java-solution-using-priorityqueue/12


The correctness of this algorithm is based on the fact that each time we only examine the boarder point with the smallest height and we traverse from outside boarder to insider point. So each time you encounter with a point in the graph with a smaller height, you are guaranteed to be able to hold at least cell.height - heights[row][col] water in this point (remember that current cell we used are the one with the smallest height among the boarders).



public class Solution {    public static int trapRainWater(int[][] heightMap){int m=heightMap.length;if(m<=2)return 0;int n=heightMap[0].length;if(n<=2)return 0;int[] xoff={-1,1,0,0};int[] yoff={0,0,1,-1};boolean[][] isVisited=new boolean[m][n];PriorityQueue<trwNode> priorityqueue=new PriorityQueue<>();for(int i=0;i<m;i++){isVisited[i][0]=true;isVisited[i][n-1]=true;priorityqueue.add(new trwNode(i, 0, heightMap[i][0]));priorityqueue.add(new trwNode(i, n-1, heightMap[i][n-1]));}for(int j=1;j<n-1;j++){isVisited[0][j]=true;isVisited[m-1][j]=true;priorityqueue.add(new trwNode(0, j, heightMap[0][j]));priorityqueue.add(new trwNode(m-1, j, heightMap[m-1][j]));}int sum=0;while(!priorityqueue.isEmpty()){trwNode node=priorityqueue.poll();int x=node.x;int y=node.y;for(int k=0;k<4;k++){int xx=x+xoff[k];int yy=y+yoff[k];if(xx>=0&&xx<m&&yy>=0&&yy<n&&!isVisited[xx][yy]){isVisited[xx][yy]=true;sum+=Math.max(0, node.height-heightMap[xx][yy]);priorityqueue.add(new trwNode(xx, yy, Math.max(node.height, heightMap[xx][yy])));}}}return sum;}}class trwNode implements Comparable<trwNode>{int x,y;int height;public trwNode(int x,int y,int height){this.x=x;this.y=y;this.height=height;// TODO Auto-generated constructor stub}@Overridepublic int compareTo(trwNode o){// TODO Auto-generated method stubint cmp=height-o.height;if(cmp>0)return 1;else if(cmp<0)return -1;return 0;}@Overridepublic String toString(){// TODO Auto-generated method stubreturn "("+x+","+y+")";}}


0 0
原创粉丝点击