Leetcode 407:trapping Rain Water II

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.