JAVA程序设计:接雨水 II(LeetCode:407)

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

 

说明:

m 和 n 都是小于110的整数。每一个单位的高度都大于 0 且小于 20000。

 

示例:

给出如下 3x6 的高度图:
[
  [1,4,3,1,3,2],
  [3,2,1,3,2,4],
  [2,3,3,2,3,1]
]

返回 4。

思路:我们可以采用优先队列的做法,其中优先队列按照高度升序排序,将所有边界点加进优先队列,然后我们从队头进行广搜,并标记所有访问过的点,每次将当前位置能放水的最大高度加入答案即可。

class Solution {
	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<=2 || heightMap.length<=2)
        	return 0;
        PriorityQueue<Cell> queue=new PriorityQueue<>(Comparator.comparingInt((Cell cell)->cell.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]=visited[i][n-1]=true;
        	queue.add(new Cell(i,0,heightMap[i][0]));
        	queue.add(new Cell(i,n-1,heightMap[i][n-1]));
        }
        for(int i=1;i<n-1;i++) {
        	visited[0][i]=visited[m-1][i]=true;
        	queue.add(new Cell(0,i,heightMap[0][i]));
        	queue.add(new Cell(m-1,i,heightMap[m-1][i]));
        }
        int ans=0;
        int[][] bounds= {{-1,0},{1,0},{0,-1},{0,1}};
        while(!queue.isEmpty()) {
        	Cell now=queue.poll();
        	for(int[] bound : bounds) {
        		int row=now.row+bound[0];
        		int col=now.col+bound[1];
        		if(row>=0 && row<m && col>=0 && col<n && !visited[row][col]) {
        			ans+=Math.max(0, now.height-heightMap[row][col]);
        			visited[row][col]=true;
        			queue.add(new Cell(row,col,Math.max(heightMap[row][col],now.height)));
        		}
        	}
        }
        return ans;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值