Note:
The update height with MAX (current height, real height) was because how many water this block can held depends on all Outsi De Heights.
Another thought is if we traversed to this block, we found that it have been filled with water and then we make it Heig HT as the max (min (all neighbors), current height) to make it flat.
classSolution {classBlock {intx; inty; intheight; PublicBlock (intXintYintheight) { This. x =x; This. y =y; This. Height =height; } } Public intTraprainwater (int[] heightmap) { if(Heightmap.length < 3)return0; Priorityqueue<Block> queue =NewPriorityqueue<> (B1, B2), B1.height-b2.height); Boolean[] visited =New Boolean[Heightmap.length] [Heightmap[0].length]; for(inti = 0; i < heightmap.length; i++) {visited[i][0] =true; visited[i][heightmap[0].LENGTH-1] =true; Queue.offer (NewBlock (i, 0, heightmap[i][0])); Queue.offer (NewBlock (i, Heightmap[0].length-1, heightmap[i][heightmap[0].length-1])); } for(inti = 0; i < heightmap[0].length; i++) {visited[0][i] =true; Visited[heightmap.length-1][i] =true; Queue.offer (NewBlock (0, I, heightmap[0][i])); Queue.offer (NewBlock (Heightmap.length-1, I, heightmap[heightmap.length-1][i])); } int[] dirs =New int[] {{0, 1}, {0,-1}, {1, 0}, {-1, 0}}; intresult = 0; while(!Queue.isempty ()) {Block current=Queue.poll (); for(int[] dir:dirs) { intx = current.x + dir[0]; inty = current.y + dir[1]; if(x >= 0 && x < heightmap.length && y >= 0 && y < heightmap[0].length &&!)Visited[x][y]) {Visited[x][y]=true; Result+ = Math.max (0, Current.height-Heightmap[x][y]); Queue.offer (NewBlock (x, Y, Math.max (heightmap[x][y], current.height))); } } } returnresult; }}
Leetcode 407:trapping Rain Water II