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
Example 1:
Given `5*4` matrix
Input:
[[12,13,0,12],[13,4,13,12],[13,8,10,12],[12,13,12,12],[13,13,13,13]]
Output:
14
Example 2:
Input:
[[2,2,2,2],[2,2,3,4],[3,3,3,1],[2,3,4,5]]
Output:
0
思路:一个格子能够盛水的高度,取决于这个格子四个方向能够传进来吃水线的最小值;用priorityqueue,最外围的格子是不能装水的,然后从最小的吃水线往里面渗透,因为每次都是以最小的吃水线往里面传递,那么保证了每次算出来的吃水线-height都是合法的盛水的高度;m*nlog(m*n);
class Solution {
private class Node {
public int x;
public int y;
public int height;
public Node(int x, int y, int height) {
this.x = x;
this.y = y;
this.height = height;
}
}
public int trapRainWater(int[][] heightMap) {
if(heightMap == null || heightMap.length == 0 || heightMap[0].length == 0) {
return 0;
}
int m = heightMap.length;
int n = heightMap[0].length;
PriorityQueue<Node> pq = new PriorityQueue<Node>((a, b) -> (a.height - b.height));
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(i == 0 || i == m - 1 || j == 0 || j == n - 1) {
pq.offer(new Node(i, j, heightMap[i][j]));
}
}
}
boolean[][] visited = new boolean[m][n];
int[][] dirs = {{0,1},{0,-1},{-1,0},{1,0}};
int water = 0;
while(!pq.isEmpty()) {
Node node = pq.poll();
int x = node.x;
int y = node.y;
int height = node.height;
if(visited[x][y]) {
continue;
}
if(height > heightMap[x][y]) {
water += height - heightMap[x][y];
}
visited[x][y] = true;
for(int[] dir: dirs) {
int nx = node.x + dir[0];
int ny = node.y + dir[1];
if(0 <= nx && nx < m && 0 <= ny && ny < n && !visited[nx][ny]) {
pq.offer(new Node(nx, ny, Math.max(height, heightMap[nx][ny])));
}
}
}
return water;
}
}