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.
思路:
求两个矩形的覆盖面积。如果两个矩形没有交叉,那么覆盖面积就是两个矩形的面积之和;如果有交叉,那么结果等于两个矩形的面积和剪去交叉的面积。
交叉面积实质是求交叉面积的长和宽,长和宽其实是要求交叉面积的左右上下坐标。
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
//相交
int left = 0, right = 0, top = 0, bottom = 0;
left = Math.max(A, E);
right = Math.min(C, G);
top = Math.min(D, H);
bottom = Math.max(B, F);
return (C - A) * (D - B) - (right - left) * (top - bottom) + (G - E) * (H - F);
}