题目:
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 computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
//计算第一个矩形的面积
int s1 = (C - A) * (D - B);
int s2 = (G - E) * (H - F);
int point_low[2] = { 0 };
int point_high[2] = { 0 };
//先判断x轴的坐标关系A-C与E-G
if (G <= A) //第二个矩形在第一个矩形的左边,两者不相交
{
return s1 + s2;
}
if (G >A && G <= C) //第二个矩形与第一个矩形可能有重叠的部分
{
if (H <= B || F >= D) //第二个矩形与第一个矩形不重叠
{
return s1 + s2;
}
else{
point_high[0] = (G < C) ? G : C;
point_high[1] = (H < D) ? H : D;
point_low[0] = (E > A) ? E : A;
point_low[1] = (F > B) ? F : B;
return (s1 + s2 - (point_high[0] - point_low[0]) * (point_high[1] - point_low[1]));
}
}
if (G > C) //第二个矩形与第一个矩形可能有重叠的部分
{
if (E >= C) //第二个矩形与第一个矩形不重叠
{
return s1 + s2;
}
else{ //第二个矩形与第一个矩形可能有重叠的部分
if (F >= D || H < B) //第二个矩形与第一个矩形不重叠
{
return s1 + s2;
}
else{
point_high[0] = (G < C) ? G : C;
point_high[1] = (H < D) ? H : D;
point_low[0] = (E > A) ? E : A;
point_low[1] = (F > B) ? F : B;
}
return (s1 + s2 - (point_high[0] - point_low[0]) * (point_high[1] - point_low[1]));
}
}
}
};
结果:
思路: