题目:
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.
Assume that the total area is never beyond the maximum possible value of int.
思想:
求两个长方形覆盖的最大面积。假设二者的面积分别为s1,s2,重合部分的面积为c1。在二者不重合的情况下,只需分别计算二者的面积相加s1+s2。若出现重合则为s1+s2-c1。设重合部分的长方形的两个对角点的坐标分别为a,b,c,d。由题意可得a,b,c,d的值如下代码所示。
代码:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int a, b, c, d, w, h;
if (E>C || F>D || B>H || A>G)//二者没有交集
return (C-A)*(D-B)+(G-E)*(H-F);
a = max(A, E);//计算出重复部分的面积
b = max(B, F);
c = min(C, G);
d = min(D, H);
w = max(a, c) - min(a, c);
h = max(b, d) - min(b, d);
return (C - A)*(D - B) + (G - E)*(H - F)-w*h;//有交集,减去重复部分
}