用优先队列,把边沿的墙全加进去,然后从最低的开始,看四周要不要补水。其他的和第一题很像
public class Solution {
class cell implements Comparable{
int x;
int y;
int height;
public cell(int x, int y, int height) {
this.x = x;
this.y = y;
this.height = height;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
@Override
public int compareTo( Object o) {
cell oo = (cell) o;
return height-((cell) o).getHeight();
}
}
public int trapRainWater(int[][] heightMap) {
int width = heightMap.length;
if(width<=0)return 0;
int length = heightMap[0].length;
boolean [][]visted = new boolean[width][length];
PriorityQueue<cell> priorityQueue = new PriorityQueue<>();
if (width == 0 || length == 0)return 0;
for (int i=0;i<width;i++){
visted[i][length-1] = true;
visted[i][0] = true;
priorityQueue.add(new cell(length-1,i,heightMap[i][length-1]));
priorityQueue.add(new cell(0,i,heightMap[i][0]));
}
for (int i=0;i<length;i++){
visted[width-1][i] = true;
visted[0][i] =true;
priorityQueue.add(new cell(i,width-1,heightMap[width-1][i]));
priorityQueue.add(new cell(i,0,heightMap[0][i]));
}
int res = 0;
int[][] fangxiang = {{0,1},{0,-1},{-1,0},{1,0}};
while (!priorityQueue.isEmpty()){
cell ce = priorityQueue.poll();
//System.out.println("height:"+ce.getHeight());
for (int i=0;i<fangxiang.length;i++){
int dx = ce.getX()+fangxiang[i][0];
int dy = ce.getY()+fangxiang[i][1];
if (dx>=0&&dx<length&&dy>=0&&dy<width) {
if(!visted[dy][dx]){
cell newCell = new cell(dx, dy, heightMap[dy][dx]);
visted[dy][dx] = true;
if (ce.compareTo(newCell)>0){
res+=ce.compareTo(newCell);
// System.out.println("res:"+res);
newCell.setHeight(ce.getHeight());
priorityQueue.add(newCell);
continue;
}else {
priorityQueue.add(newCell);
}
}
}
}
}
return res;
}
}
本文介绍了一种使用优先队列实现的雨水捕捉算法。该算法通过将地图边界上的高度加入优先队列,并逐步填充内部区域来计算可以捕捉多少雨水。具体步骤包括初始化队列、更新已访问标记、比较周围单元格高度等。
390

被折叠的 条评论
为什么被折叠?



