LeetCode Q 407 - Trapping Rain Water II
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.
Solution
Solution 1: Heap
Code:
public int trapRainWater(int[][] heightMap) {
if (heightMap == null || heightMap.length == 0) return 0;
int R = heightMap.length, C = heightMap[0].length;
Queue<int[]> pq = new PriorityQueue<>((a,b) -> (a[2] - b[2]));
boolean[][] visited = new boolean[R][C];
for (int r = 0; r < R; r++) {
pq.offer(new int[]{r, 0, heighMap[r][0]}); visited[r][0] = true;
pq.offer(new int[]{r, C - 1, heighMap[r][C - 1]}); visited[r][C - 1] = true;
}
for (int c = 0; c < C; c++) {
pq.offer(new int[]{0, c, heighMap[0][c]}); visited[0][c] = true;
pq.offer(new int[]{R - 1, c, heighMap[R - 1][c]}); visited[R - 1][c] = true;
}
int res = 0;
int[] dirs = new int[] {1, 0, -1, 0, 1};
while (!pq.isEmpty()) {
int[] curr = pq.poll();
for (int i = 0; i < 4; i++) {
int nr = curr[0] + dirs[i];
int nc = curr[1] + dirs[i + 1];
if (nr >= 0 && nc >= 0 && nr < R && nc < C && !visited[nr][nc]) {
visited[nr][nc] = true;
pq.offer(new int[]{nr, nc, Math.max(curr[2], heightMap[nr][nc])});
res += Math.max(0, curr[2] - heightMap[nr][nc]);
}
}
}
return res;
}