(int[][] heightMap)
| 1 | class Solution { |
| 2 | |
| 3 | public int trapRainWater(int[][] heightMap) { |
| 4 | //left,right,down, up |
| 5 | int dir[][] = {{0,-1},{0,1},{-1,0},{1,0}}; |
| 6 | int rows = heightMap.length; |
| 7 | int cols = heightMap[0].length; |
| 8 | if(rows <3 || cols <3) return 0; |
| 9 | int totalUnvisitedCells = rows*cols; |
| 10 | boolean[][] visited = new boolean[rows][cols]; |
| 11 | // [hight, row, col] -> inc order of height |
| 12 | PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> (a[0]-b[0])); |
| 13 | |
| 14 | for (int i = 0; i < rows; i++) { |
| 15 | pq.offer(new int[]{heightMap[i][0], i, 0}); |
| 16 | pq.offer(new int[]{heightMap[i][cols - 1], i, cols - 1}); |
| 17 | visited[i][0] = true; |
| 18 | visited[i][cols - 1] = true; |
| 19 | totalUnvisitedCells--; |
| 20 | totalUnvisitedCells--; |
| 21 | } |
| 22 | |
| 23 | for (int i = 1; i < cols-1; i++) { |
| 24 | pq.offer(new int[]{heightMap[0][i], 0, i}); |
| 25 | pq.offer(new int []{heightMap[rows - 1][i], rows - 1, i}); |
| 26 | visited[0][i] = true; |
| 27 | visited[rows - 1][i] = true; |
| 28 | totalUnvisitedCells--; |
| 29 | totalUnvisitedCells--; |
| 30 | } |
| 31 | int trappedWater = 0; |
| 32 | int waterLevel=0; |
| 33 | //n*mlog(n*m) |
| 34 | while (!pq.isEmpty() && totalUnvisitedCells>0) { |
| 35 | int currentCell[] = pq.poll(); |
| 36 | int currentHeight = currentCell[0]; |
| 37 | int currentRow = currentCell[1]; |
| 38 | int currentCol = currentCell[2]; |
| 39 | waterLevel = Math.max(waterLevel, currentHeight); |
| 40 | // Explore all 4 neighboring cells |
| 41 | for (int direction = 0; direction < 4; direction++) { |
| 42 | int neighborRow = currentRow + dir[direction][0]; |
| 43 | int neighborCol = currentCol + dir[direction][1]; |
| 44 | // Check if the neighbor is within the grid bounds and not yet visited |
| 45 | if (isValidCell(neighborRow,neighborCol,rows,cols) && !visited[neighborRow][neighborCol]) { |
| 46 | int neighborHeight = heightMap[neighborRow][neighborCol]; |
| 47 | if (neighborHeight < waterLevel) { |
| 48 | trappedWater += waterLevel - neighborHeight; |
| 49 | } |
| 50 | pq.offer(new int[]{neighborHeight,neighborRow,neighborCol}); |
| 51 | visited[neighborRow][neighborCol] = true; |
| 52 | totalUnvisitedCells--; |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | return trappedWater; |
| 57 | } |
| 58 | |
| 59 | private boolean isValidCell(int row,int col,int rows,int cols) { |
| 60 | return row >= 0 && col >= 0 && row < rows && col < cols; |
nothing calls this directly
no test coverage detected