Trapping Rain Water II

本文介绍了一种基于优先队列的算法,用于计算二维矩阵在降雨后能容纳多少水。通过遍历边界元素并将它们加入优先队列,算法逐步向内渗透,确保每个单元格的积水高度等于其四周最高障碍物的最小值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given n x m non-negative integers representing an elevation map 2d where the area of each cell is 1 x 1, compute how much water it is able to trap after raining.

Example

Example 1:

Given `5*4` matrix 
Input:
[[12,13,0,12],[13,4,13,12],[13,8,10,12],[12,13,12,12],[13,13,13,13]]
Output:
14

Example 2:

Input:
[[2,2,2,2],[2,2,3,4],[3,3,3,1],[2,3,4,5]]
Output:
0

思路:一个格子能够盛水的高度,取决于这个格子四个方向能够传进来吃水线的最小值;用priorityqueue,最外围的格子是不能装水的,然后从最小的吃水线往里面渗透,因为每次都是以最小的吃水线往里面传递,那么保证了每次算出来的吃水线-height都是合法的盛水的高度;m*nlog(m*n);

class Solution {
    private class Node {
        public int x;
        public int y;
        public int height;
        public Node(int x, int y, int height) {
            this.x = x;
            this.y = y;
            this.height = height;
        }
    }
    
    public int trapRainWater(int[][] heightMap) {
        if(heightMap == null || heightMap.length == 0 || heightMap[0].length == 0) {
            return 0;
        }
        int m = heightMap.length;
        int n = heightMap[0].length;
        PriorityQueue<Node> pq = new PriorityQueue<Node>((a, b) -> (a.height - b.height));
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(i == 0 || i == m - 1 || j == 0 || j == n - 1) {
                    pq.offer(new Node(i, j, heightMap[i][j]));
                }
            }
        }
        
        boolean[][] visited = new boolean[m][n];
        int[][] dirs = {{0,1},{0,-1},{-1,0},{1,0}};
        
        int water = 0;
        while(!pq.isEmpty()) {
            Node node = pq.poll();
            int x = node.x;
            int y = node.y;
            int height = node.height;
            if(visited[x][y]) {
                continue;
            }
            if(height > heightMap[x][y]) {
                water += height - heightMap[x][y];
            }
            visited[x][y] = true;
            for(int[] dir: dirs) {
                int nx = node.x + dir[0];
                int ny = node.y + dir[1];
                if(0 <= nx && nx < m && 0 <= ny && ny < n && !visited[nx][ny]) {
                    pq.offer(new Node(nx, ny, Math.max(height, heightMap[nx][ny])));
                }
            }
        }
        return water;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值