1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| class Solution { private static class Cell { int row; int col; int height;
Cell(int _row, int _col, int _height) { row = _row; col = _col; height = _height; } }
public int trapRainWater(int[][] heightMap) { PriorityQueue<Cell> pq = new PriorityQueue<>((a, b) -> a.height - b.height); boolean[][] visited = new boolean[heightMap.length][heightMap[0].length]; for (int i = 0; i < heightMap[0].length; i++) { pq.offer(new Cell(0, i, heightMap[0][i])); visited[0][i] = true; pq.offer(new Cell(heightMap.length - 1, i, heightMap[heightMap.length - 1][i])); visited[heightMap.length - 1][i] = true; } for (int i = 1; i < heightMap.length - 1; i++) { pq.offer(new Cell(i, 0, heightMap[i][0])); visited[i][0] = true; pq.offer(new Cell(i, heightMap[0].length - 1, heightMap[i][heightMap[0].length - 1])); visited[i][heightMap[0].length - 1] = true; } int ans = 0; int[][] directions = new int[][] { { -1, 0 }, { 1, 0 }, { 0, 1 }, { 0, -1 } }; while (!pq.isEmpty()) { Cell currCell = pq.poll(); for (int[] direction : directions) { int newRow = currCell.row + direction[0]; int newCol = currCell.col + direction[1]; if (!isOutOfBound(heightMap, newRow, newCol) && !visited[newRow][newCol]) { visited[newRow][newCol] = true; ans += Math.max(0, currCell.height - heightMap[newRow][newCol]); pq.offer(new Cell(newRow, newCol, Math.max(currCell.height, heightMap[newRow][newCol]))); } } } return ans; }
private boolean isOutOfBound(int[][] grid, int row, int col) { return row < 0 || row >= grid.length || col < 0 || col >= grid[0].length; } }
|