Topic:
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.
Translation:
In a two-dimensional plane, the total area covered by 2 rectangles surrounded by a straight line is calculated.
Each rectangle is defined by its lower-left corner and the point at the upper-right corner.
Analysis:
The key to this problem is the need to draw a picture to clarify what might happen.
1.2 rectangles do not intersect, this side is divided into 2 cases, one is the second rectangle above or below the first rectangle, one is the second rectangle on the left or the right of the first rectangle, or maybe 2, but because of the relationship is or, so do not consider.
2.2 rectangles intersect, the intersection is actually put 4 x-axis together, find the size in the middle of the 2, as the x-axis;
Code:
Public classSolution { Public int Computearea(intAintBintCintDintEintFintGintH) {intsum= (c-a) * (d-b) + (G-E) * (H-F);if(c<e| | g<a| | h<b| | D<F) {//No crossover returnSum }Else{//With crossover //Calculate the x-coordinate of the overlapping part, ACEG intX1=a<e? e:a;intX2=c<g? C:g;//Calculate the y-coordinate of the overlapping part, BDFH intY1=b<f? F:b;intY2=dreturnsum-(x2-x1) * (Y2-Y1); } }}
Leet Code OJ 223. Rectangle area [Difficulty:easy]