https://leetcode.com/problems/trapping-rain-water-ii/
// https://discuss.leetcode.com/topic/60418/java-solution-using-priorityqueue/2
// 这个解法真的好棒,真的太棒了
// 一维的也能搞定
// 利用一个PriorityQueue,从小往大排的
import java.util.Comparator;
import java.util.PriorityQueue;
public class Solution {
public class Cell {
int row;
int col;
int height;
public Cell(int r, int c, int h) {
row = r;
col = c;
height = h;
}
}
public int trapRainWater(int[][] heightMap) {
if (heightMap == null || heightMap.length == 0 || heightMap[0].length == 0) {
return 0;
}
int rows = heightMap.length;
int cols = heightMap[0].length;
boolean [][]visited = new boolean[rows][cols];
// 注意,是从小往大排
PriorityQueue<Cell> pq = new PriorityQueue<Cell>(1, new Comparator<Cell>(){
public int compare(Cell a, Cell b) {
return a.height - b.height;
}
});
for (int i=0; i<rows; i++) {
visited[i][0] = true;
visited[i][cols-1] = true;
pq.offer(new Cell(i, 0, heightMap[i][0]));
pq.offer(new Cell(i, cols-1, heightMap[i][cols-1]));
}
for (int i=0; i<cols; i++) {
visited[0][i] = true;
visited[rows-1][i] = true;
pq.offer(new Cell(0, i, heightMap[0][i]));
pq.offer(new Cell(rows-1, i, heightMap[rows-1][i]));
}
int result = 0;
int [][]dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
while (!pq.isEmpty()) {
Cell cl = pq.poll();
for (int i=0; i<4; i++) {
int r = cl.row + dirs[i][0];
int c = cl.col + dirs[i][1];
if (r < 0 || r >= rows || c < 0 || c >= cols || visited[r][c]) {
continue;
}
int newHt = heightMap[r][c];
if (heightMap[r][c] < cl.height) {
result += cl.height - heightMap[r][c];
newHt = cl.height;
}
pq.offer(new Cell(r, c, newHt));
visited[r][c] = true;
}
}
return result;
}
}