Leetcode407.接雨水Ⅱ

题目:

给你一个 m*n 的矩阵,其中的值均为非负整数,代表二维高度图每个单元的高度,请计算图中形状最多能接多少体积的雨水。

提示:

\\m = heightMap.length\\ n = heightMap[i].length\\ 1 <= m, n <= 200\\ 0 <= heightMap[i][j] <= 2 * 10^4

 思路:

一个位置(i,j)所能存储水的量取决于该位置到边界各个点的路径中的各个格子的最高值的最小值。那么使用最小堆的思想,堆中最小高度的格子更新出来周围格子的储水量一定是满足要求的,将该格子出堆,将新更新的格子存储到最小堆中。使用宽度优先遍历即可得到最终结果。

class Solution {
    public int trapRainWater(int[][] h) {
        PriorityQueue<int[]> q = new PriorityQueue<>((a,b) -> a[0]-b[0]);
        int res = 0;
        int n = h.length, m = h[0].length;
        int[] dx = new int[]{1,0,-1,0};
        int[] dy = new int[]{0,1,0,-1};
        boolean[][] st = new boolean[n][m];
        for(int i = 0;i < n;i++) {
            q.offer(new int[]{h[i][0],i,0});
            st[i][0] = true;
            q.offer(new int[]{h[i][m-1],i,m-1});
            st[i][m-1] = true;
        }
        for(int i = 1;i < m -1;i++) {
            q.offer(new int[]{h[0][i],0,i});
            st[0][i] = true;
            q.offer(new int[]{h[n-1][i],n-1,i});
            st[n-1][i] = true;
        }
        while(q.size() > 0) {
            int[] x = q.poll();
            res += x[0] - h[x[1]][x[2]];
            for(int i = 0;i < 4;i++) {
                int xx = x[1] + dx[i],yy = x[2] + dy[i];
                if(xx >= 0 && xx < n && yy >= 0 && yy < m && !st[xx][yy]) {
                    q.offer(new int[]{Math.max(h[xx][yy],x[0]),xx,yy});
                    st[xx][yy] = true;
                }
            }
        }
        return res;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值