Rectangle Area
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.
Credits:
Special thanks to @mithmatt for adding this problem, creating the above image and all test cases.
The sum of the two rectangles minus the overlapping area of each area.
Note (A, b) (C,d) represents the first rectangle Rect1, (e,f) (G,h) that represents Rect2
First, there are 4 cases, rect1 and rect2 completely do not overlap
1, rect1 the entire rect2 to the right, namely A >= G
2, rect1 the entire rect2 to the left, namely C <= E
3, rect1 the entire rect2 top, that is, B >= H
4, rect1 the entire rect2 below, namely D <= F
Second, calculate overlapping area (that is, length, width)
1, Calculate the width
(1) When A <= E,
The leftmost part of the overlapping section is the leftmost side of the Rect2 (E)
The rightmost part of the overlap may be the rightmost (C) of the rect1, or it may be the rightmost (G) of the Rect2
(2) When A > E,
The leftmost part of the overlapping section is the leftmost side of the Rect1 (A)
The rightmost part of the overlap may be the rightmost (C) of the rect1, or it may be the rightmost (G) of the Rect2
2, calculate the length
(1) When D <= H,
The topmost part of the overlapping section is the top of the Rect1 (D)
The bottom of the overlapping section may be the bottom (B) of the rect1, or it may be the bottom of the Rect2 (F)
(2) When D > H,
The topmost part of the overlapping section is the top of the Rect2 (H)
The bottom of the overlapping section may be the bottom (B) of the rect1, or it may be the bottom of the Rect2 (F)
classSolution { Public: intComputearea (intAintBintCintDintEintFintGintH) {intwidth; intheight; if(A >= G//Rect1 is in the right of Rect2|| C <= E//Rect1 is in the left of Rect2|| B >= H//Rect1 is above Rect2|| D <= F//Rect1 is below Rect2 ) {//no overlapwidth =0; Height=0; } Else {//overlap if(A <=E) Width= Min (g-e, C-E); Elsewidth= Min (c-a, G-A); if(D <=H) Height= Min (d-b, D-F); ElseHeight= Min (h-f, H-B); } return(c-a) * (d-b) + (G-E) * (h-f)-height*width; }};
"Leetcode" 223. Rectangle Area