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.
就是先判断两矩形的相对关系,是否相离(两矩形面积直接相加),相交(两矩形面积相加之后再减掉重合部分面积),包含(直接返回包含矩形的面积);
再根据不同的关系进行计算;
class Solution {
public:
int Max(int x, int y) {
if (x > y)
return x;
else
return y;
}
int Min(int x, int y) {
if (x < y)
return x;
else
return y;
}
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
if (E > C || A > G || B > H || F > D)
return (C - A)*(D - B) + (G - E)*(H - F);
int xleftdown = Max(A, E);
int yleftdown = Max(B, F);
int xrightup = Min(C, G);
int yrightup = Min(D, H);
if (xleftdown == E && yleftdown == F && xrightup == G && yrightup == H)
return (C - A)*(D - B);
else if (xleftdown == A && yleftdown == B && xrightup == C && yrightup == D)
return (G - E)*(H - F);
else
return (C - A)*(D - B) + (G - E)*(H - F)-(xrightup - xleftdown)*(yrightup - yleftdown);
}
};