Find the total area covered by two rectilinear rectangles in a 2D plane.
Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
Example:
Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45
Note:
Assume that the total area is never beyond the maximum possible value of int.
LeetCode:
是的升级版。
如果两个矩形不相交,总面积就是两个矩形的面积,如果两个矩形相交,总面积就是两个矩形的面积和 - 公共面积。实际上就是让我们求公共面积。
class Solution(object):
def computeArea(self, A, B, C, D, E, F, G, H):
"""
:type A: int
:type B: int
:type C: int
:type D: int
:type E: int
:type F: int
:type G: int
:type H: int
:rtype: int
"""
xmin = max(A, E)
xmax = min(C, G)
ymin = max(B, F)
ymax = min(D, H)
width = xmax - xmin
height = ymax - ymin
size = (C-A)*(D-B) + (G-E)*(H-F)
overlap = width * height if width and height else 0
return size - overlap