Easy level which probably means easy to make mistakes......
Better to draw a graph to make the question clear.....
Under these situations, there is no overlap.
Thus, G <= A || E >= C || G <= B || F >= D.... there is no overlap, the total area is the sum of two cubes area
For the overlap situation, we just need to consider one situation, all the overlaps will be the same anyway....
The easiest one would be one is totally inside the other one.
In this case, the overlap area woud be overlap = abs(min(G, C) - max(A, E)) * abs(max(B, F) - min(D, H));
Thus the total area is The sum of two cubes area - overlap.....
Generate code would be easy then.....
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
if(E >= C || G <= A || H <= B || D <= F) return (C-A)*(D-B)+(G-E)*(H-F);
else {
return (C-A)*(D-B)+(G-E)*(H-F) - (min(C, G) - max(A, E)) * (min(H, D) - max(B, F));
}
}
本文介绍了一种计算两个二维矩形重叠面积的方法。首先判断两矩形是否有重叠,若无重叠则总面积为两矩形面积之和;若有重叠,则计算重叠部分的面积并从总面积中减去。文章给出了具体的数学公式和实现代码。
733

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



