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