Well, this problem looks easy at first glance. However, to get a bug-free code may is not this easy.
The total square was simply equal to the sum of the area of the rectangles minus the area of their overlap. How does we compute the area of a rectangle? Well, the simply times its height and its width. The height and width can obtained from the coordinates of the corners.
The key to this problem actually lies on how to handle overlap.
First, let's think about when overlap would happen? Well, if one rectangle was completely to the left or right of the other and then no overlap would happen; Otherwise, it'll.
How does we know whether a rectangle is completely to the left of the other? Well, just make sure then the right boundary of it was to the left of the the "the other." That's, C <= E . The right case can is handled similarly by A >= G .
Now we know how to check for overlap. If overlap happens, how do we compute it? The key is to find the boundary of the overlap.
Take the image at the problem statement as an example. It can be seen max(A, E) the boundary of the overlap are, the right boundary is min(C, G) . The top and bottom boundaries are min(D, H) and max(B, F) similarly. The overlap is simply (min(C, G) - max(A, E)) * (min(D, H) - max(B, F)) .
You should now convince yourself-all kind of overlapping cases can is handled by the above formula by drawing some ex Amples on the paper.
Finally, we have the following code (simply a translation of the above idea).
1 intComputearea (intAintBintCintDintEintFintGintH) {2 intS1 = (c-a) * (D-B); 3 intS2 = (g-e) * (H-F);4 if(A >= G | | C <=E)5 returnS1 +S2; 6 returnS1 + S2-(min (C, G)-Max (A, E)) * (min (D, H)-Max (B, F));7}
[Leetcode] Rectangle Area