day-08:接雨水

class Solution {
    private static class Cell implements Comparable<Cell> {
		int row;
		int col;
		int height;

		public Cell(int row, int col, int height) {
			this.row = row;
			this.col = col;
			this.height = height;
		}

		@Override
		public int compareTo(Cell o) {
			return this.height - o.height;
		}
	}

	public static int trapRainWater(int[][] heightMap) {
		if (heightMap.length <= 1 || heightMap[0].length <= 1) {
			return 0;
		}
		boolean[][] visited = new boolean[heightMap.length][heightMap[0].length];
		PriorityQueue<Cell> queue = new PriorityQueue<Cell>();
		int waterTraped = 0;
	
		for (int j = 0; j < heightMap[0].length; j++) {
			queue.add(new Cell(0, j, heightMap[0][j]));
			queue.add(new Cell(heightMap.length - 1, j,
					heightMap[heightMap.length - 1][j]));
			visited[0][j] = true;
			visited[heightMap.length - 1][j] = true;
		}
		for (int i = 1; i < heightMap.length - 1; i++) {
														
			queue.add(new Cell(i, 0, heightMap[i][0]));
			queue.add(new Cell(i, heightMap[0].length - 1,
					heightMap[i][heightMap[0].length - 1]));
			visited[i][0] = true;
			visited[i][heightMap[0].length - 1] = true;
		}
		
		Cell lowestWall;
		int row, col;
		int[][] direction = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };
		while (!queue.isEmpty()) {
			lowestWall = queue.poll();
			for (int i = 0; i < 4; i++) {
				row = lowestWall.row + direction[i][0];
				col = lowestWall.col + direction[i][1];
				if (row < 0 || row > heightMap.length - 1 || col < 0
						|| col > heightMap[0].length - 1
						|| visited[row][col] == true) {
					continue;
				}
				waterTraped += Math.max(
						lowestWall.height - heightMap[row][col], 0);
				queue.add(new Cell(row, col, Math.max(lowestWall.height,
						heightMap[row][col])));
				visited[row][col] = true;
			}
		}
		return waterTraped;
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值