Leetcode 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.


The above image represents the elevation map [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] before the rain.

三维的装水的问题,主要思路还是从边缘的地方开始找。

priorityqueue每次poll出最高优先级的元素,也就是目前height最高的元素。

对于visit之后的元素来说,新的高度是要updata的,要么保持原样,要么变成装了水之后的高度。

public class Solution {
    
    private class Cell {
        private int row;
        private int col;
        private int height;
        
        public Cell(int row, int col, int height){
            this.row = row;
            this.col = col;
            this.height = height;
        }
    }
    
    
    public int trapRainWater(int[][] heightMap) {
        if(heightMap == null || heightMap.length == 0 ||heightMap[0].length == 0) {
            return 0;
        }
        
        PriorityQueue<Cell> queue = new PriorityQueue<>(1, new Comparator<Cell>(){
            public int compare(Cell a, Cell b) {
                return a.height - b.height;
            }
        });
        
        int m = heightMap.length;
        int n = heightMap[0].length;
        boolean[][] visited = new boolean[m][n];
        
        for (int i = 0; i< m ;i++){
            visited[i][0] = true;
            visited[i][n-1] = true;
            queue.offer(new Cell(i, 0, heightMap[i][0]));
            queue.offer(new Cell(i, n-1, heightMap[i][n-1]));
        }
        
        for (int i = 0; i< n ;i++){
            visited[0][i] = true;
            visited[m-1][i] = true;
            queue.offer(new Cell(0, i, heightMap[0][i]));
            queue.offer(new Cell(m-1, i, heightMap[m-1][i]));
        }
        
        
        
        int[][] dirs = new int[][]{{-1,0},{1,0},{0,-1},{0,1}};
        int res = 0;
        while(!queue.isEmpty()){
            Cell cell = queue.poll();
            for(int[] dir : dirs){
                int row = cell.row + dir[0];
                int col = cell.col + dir[1];
                if(row >= 0 && row < m && col >=0 && col < n && !visited[row][col]){
                    visited[row][col] = true;
                    res += Math.max(0,cell.height - heightMap[row][col]);
                    queue.offer(new Cell(row,col,Math.max(heightMap[row][col],cell.height)));
                }
            }
        }
        return res;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值