Problem Definition:
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.
Solution:
There are three types of horizontal directions:
1) A-------------C
E--------------G
Or
E--------------G
A-------------C
Condition: e>g| | A>g
2) A--------------C
E-----G
Or
E-------------------G
A-----------C
Conditions: ((c>g) && (e>a)) | | ((g>c) && (a>e))
3) A-------------C
E--------------G
Or
E--------------G
A-------------C
Condition: The rest of the situation
Perpendicular to the same direction.
Code:
1 defComputearea (self, A, B, C, D, E, F, G, H):2 ifE>=corA>=gorF>=dorb>=H:3 return(c-a) * (d-b) + (G-E) * (H-F)4 ifC>g andE>A:5a=g-E6 elifG>c andA>E:7a=c-A8 Else:9A=min (g-a,c-E)Ten ifD>h andF>B: Oneb=h-F A elifH>d andB>F: -b=d-B - Else: theB=min (h-b,d-F) -dup=a*b - return(c-a) * (d-b) + (G-E) * (h-f)-dup
A more convenient way to do this:
1 def Computearea (self, A, B, C, D, E, F, G, H): 2 AREAA = (c-a) * (D- B)3 Areab = (g-e) * (H- F)4 l = max (0, Min (C, G)-< c11> Max (A, E))5 h = max (0, Min (D, h)- Max (B, F))6 return AREAA + areab-l * H
leetcode#223 Rectangle Area