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.
一开始,我想的是,遍历每一点,如果周围四个方向的最大值都大于我,那么我是可以被hold住的,因此res + h, 但是最后需要加一步,连通的水柱之间要取最小值,因为水会向低的地方流。
正解:水漫金山。把四周的高度都加进pq,每次从pq里最小的往里面漫,由于四周都大于它,因此一定能hold住,而且漫的水柱是最终答案,然后更新当前高度为最大值,再从pq里的最小往里面漫,重复上述步骤。
class Solution {
class Cell {
int x;
int y;
int h;
public Cell(int x , int y, int h){
this.x = x;
this.y = y;
this.h = h;
}
}
private static final Comparator<Cell> comparator = new Comparator<Cell>(){
public int compare(Cell a, Cell b){
return a.h - b.h;
}
};
private static final int[] x_dirs = new int[]{1, -1 , 0, 0};
private static final int[] y_dirs = new int[]{0, 0 ,1, -1};
public int trapRainWater(int[][] heightMap) {
if(heightMap == null || heightMap.length == 0 || heightMap[0].length == 0)
return 0;
final int M = heightMap.length;
final int N = heightMap[0].length;
PriorityQueue<Cell> pq = new PriorityQueue<>(comparator);
boolean visited[][] = new boolean[M][N];
//Adding boundaries to pq
for(int i = 0 ; i < M; i++){
pq.offer(new Cell(i, 0, heightMap[i][0]));
pq.offer(new Cell(i, N-1, heightMap[i][N-1]));
visited[i][0] = true;
visited[i][N-1] = true;
}
for(int i = 0 ; i < N; i++){
pq.offer(new Cell(0, i, heightMap[0][i]));
pq.offer(new Cell(M-1, i, heightMap[M-1][i]));
visited[0][i] = true;
visited[M-1][i] = true;
}
int water = 0;
while(!pq.isEmpty()){
Cell current = pq.poll();
for(int i = 0; i < 4; i++){
int nx = current.x + x_dirs[i];
int ny = current.y + y_dirs[i];
if(nx >= 0 && nx < M && ny >= 0 && ny < N && !visited[nx][ny]){
pq.offer(new Cell(nx, ny, Math.max(heightMap[nx][ny], current.h)));
//Key :: ** height of new cell.
visited[nx][ny] = true;
water = water + Math.max(0, current.h - heightMap[nx][ny]);
}
}
}
return water;
}
}