Trapping Rain Water II

来源:互联网 发布:罗斯福连任 知乎 编辑:程序博客网 时间:2024/06/06 15:53

用优先队列,把边沿的墙全加进去,然后从最低的开始,看四周要不要补水。其他的和第一题很像

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;    }}
0 0
原创粉丝点击