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.

Rectangle Area
Assume that the total area is never beyond the maximum possible value of int.

Credits:
Special thanks to @mithmatt for adding this problem, creating the above image and all test cases.

求矩形覆盖面积

思路

数学问题:
矩形覆盖面积 = 两个矩形面积之和 - 重叠部分的面积

矩形1的面积 = (C-A) * (D-B)
矩形2的面积 = (G-E) * (H-F)

然后判断是否有重叠,可以分为两部分判断,首先是判断横坐标是否有重叠;然后是纵坐标是否有重叠。横坐标就是判断矩形的宽之长w1+w2,与两个相距最远的端点横坐标之长l(图中为G-A)的长短关系,若w1+w2>l,则说明横坐标重叠;否则就完全不重叠。纵坐标同理。

当然,矩形如果为一个点或者一条线,则面积为0,自然也不存在重叠面积。

代码

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int w1 = abs(C-A);
        int h1 = abs(D-B);
        int w2 = abs(G-E);
        int h2 = abs(H-F);
        int w0 = abs(min(C,G) - max(A,E));
        int h0 = abs(max(B,F) - min(D,H));
        int a0 = w0*h0;
        if(w1*h1==0||w1+w2<=max(abs(G-A),abs(C-E))||(h1+h2)<=max(abs(D-F),abs(H-B))) {
            a0=0;
        }
        return w1*h1 + w2*h2 - a0;
    }
};