问题描述:
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.
分析:这道题的题意是获取两个矩形所覆盖的全面积,当然是两个矩形面积之和减去交叉矩形的面积,所以关键就变成了交叉面积咋求。说白了,还是求四个坐标值。
代码如下:32ms
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int row = abs(C-A);
int col = abs(D-B);
int area = row*col;
row = abs(G-E);
col = abs(H-F);
area+=row*col;
//int middle area
int left = E>A?E:A;
int right = C<G?C:G;
if(right<left)
return area;
row = right-left;
left = B>F?B:F;
right = H<D?H:D;
if(right<left)
return area;
col = right-left;
if(row<0||col<0)
return area;
return area-row*col;
}
};