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.
This topic, on the leetcode there are many so-called "a word on the realization" of the code. But I think those codes are too readable. Here is the code I wrote:
#include <stdio.h>
Calculates the portion of the two segment that is coincident, and if there is no coincident part, the output 0
With the x-axis as an example, the maximum value of the left coordinate of the two segments is found first
Find the minimum value for the right coordinate of the two line segment
Then subtract the maximum of the left coordinate with the minimum value of the right coordinate
If the subtracted value is less than 0, it means that there is no coincident
If the subtracted value is greater than or equal to 0, it indicates a coincident
The value obtained by subtracting is the length of the coincident partintCoverlength (intAintCintEintG) { intMaxA =0; if(A >E) {MaxA=A; } Else{MaxA=E; } intMinC =0; if(C <G) {MinC=C; } Else{MinC=G; } intOutint = MinC-MaxA; if(Outint <0){ return 0; } returnOutint;}intComputeretanglearea (intAintBintCintD) { return(c-a) * (D-B);}
Calculates the sum of the area of two rectangles, then subtracts the area of the coincident partintComputearea (intAintBintCintDintEintFintGintH) { intx =coverlength (A, C, E, G); inty =coverlength (B, D, F, H); intCoverarea = x*y; intFirstarea =Computeretanglearea (A, B, C, D); intLastarea =Computeretanglearea (E, F, G, H); returnFirstarea + Lastarea-Coverarea;}voidMain () {intArea = Computearea (0,0,0,0, -1, -1,1,1); printf ("%d\n", area);}
Leetcode's Rectangle area