2
public class pair implements Comparable<pair> {7
pair(int row, int col, int val) {13
public int compareTo(pair o) {14
return this.val - o.val;18
int[][] dir = {{1, 0}, {0, -1}, {-1, 0}, {0, 1}};20
public int trapRainWater(int[][] heightMap) {21
int n = heightMap.length;22
int m = heightMap[0].length;24
PriorityQueue<pair> pq = new PriorityQueue<>();26
boolean[][] visited = new boolean[n][m];28
// add all the boundary elements in pq30
for (int i = 0; i < n; i++) {31
for (int j = 0; j < m; j++) {32
if (i == 0 || j == 0 || i == n - 1 || j == m - 1) {33
pq.add(new pair(i, j, heightMap[i][j]));41
while (pq.size() > 0) {42
pair rem = pq.remove();43
for (int i = 0; i < 4; i++) {45
int rowdash = rem.row + dir[i][0];46
int coldash = rem.col + dir[i][1];52
&& visited[rowdash][coldash] == false) {53
visited[rowdash][coldash] = true;54
if (heightMap[rowdash][coldash] >= rem.val) {55
pq.add(new pair(rowdash, coldash, heightMap[rowdash][coldash])); // boundary is updated57
int waterstored = rem.val - heightMap[rowdash][coldash];58
ans += waterstored; // now this will act as a wall add in pq59
pq.add(new pair(rowdash, coldash, heightMap[rowdash][coldash] + waterstored));