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.
Credits:
Special thanks to @mithmatt for adding this problem, creating the above image and all test cases.
Subscribe to see which companies asked this question
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int width = 0, height = 0;
if(E >= C) width = 0;
else if(G <= A) width = 0;
else width = min(C,G)-max(E,A);
if(H <= B || F >= D) height = 0;
else {
int tmp1 = B > F ? B : F, tmp2 = D > H ? H : D;
height = abs(tmp2-tmp1);
}
int cover = 0;
cover = (C-A)*(D-B)+(G-E)*(H-F);
return cover - width*height;
}
};
计算两个矩形覆盖面积
本文介绍了一种计算两个直角矩形在二维平面上总覆盖面积的方法。每个矩形由其左下角和右上角定义。通过比较并计算重叠部分来得出最终结果。
409

被折叠的 条评论
为什么被折叠?



