[leetcode#223] Rectangle Area

Source: Internet
Author: User

problem:

Find the total area covered by and rectilinear rectangles in a 2D plane.

Each rectangle was defined by its bottom left corner and top right corner as shown in the figure.

Assume the total area is never beyond the maximum possible value of int.

Analysis:

The seems complex problem could is easily analyzed and sovled through simple analysis. If YouTryto analyze and distinguish in the scope of rectangle, it's too crazy to clear the relationship between them. But we could actually DoIt's a very simple. We analyze the Prolem through the separate direction:vertical direction and horizontal direction. Principle:once rectangle A in connected rectangle B, there must bes a overlay either in vertical direction or horizontal D Irection. Otherwise they could not overlay with each other. The horizontal direction:a--------------------C E--------------------------G E--------------------G A------------------------CIf the rectangles overlay with each of the other, at horizontal direction, it must meet one the above situation.        If not, they is not overlay. if(A > G | | C <E)return(h-f) * (G-E) + (d-b) * (C-A); We could also see this, since A is the left edge of C, E was the left edge of g,the left coordinate forThe overlaied rectangles is:---------------------------------------------------intleft =Math.max (A, E); the right coordinate forThe overlaied rectangles is:-------------------------------------------------------intright =math.min (C, G); The same analysis could apply to the vertical direction. Skill:to compute the overall area, we could use:total area-Overlaid area.

Solution:

 Public classSolution { Public intComputearea (intAintBintCintDintEintFintGintH) {if(A > G | | C <E)return(h-f) * (G-E) + (d-b) * (C-A); if(B > H | | D <F)return(h-f) * (G-E) + (d-b) * (C-A); intleft =Math.max (A, E); intright =math.min (C, G); intBottom =Math.max (B, F); inttop =math.min (D, H); return(h-f) * (G-E) + (d-b) * (c-a)-(top-bottom) * (right-Left ); }}

[leetcode#223] Rectangle Area

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.