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.
分析:
题意为给定两个矩形的对角坐标,求解两矩形所形成的面积大小。
本题参考博客:http://blog.youkuaiyun.com/pistolove/article/details/46868363
两个矩形要么重叠,要么不重叠!
先假设存在重叠,接着计算出重叠的四个角的坐标,如果满足大小关系(见代码)则存在,就减去重叠部分的面积。
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int result=(D-B)*(C-A)+(H-F)*(G-E);
//求取重叠部分的四个角坐标
int left = max(A, E);
int down = max(B, F);
int right = min(G, C);
int up = min(D, H);
if (up <= down || right <= left) //没有重叠
return result;
return result - (right - left) * (up - down);
}
};
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.youkuaiyun.com/ebowtang/article/details/51546418
原作者博客:http://blog.youkuaiyun.com/ebowtang
本博客LeetCode题解索引:http://blog.youkuaiyun.com/ebowtang/article/details/50668895
本文介绍了一种计算二维平面上两个矩形所覆盖总面积的方法。通过确定两个矩形是否重叠及其重叠部分的大小来计算总面积。提供了一个C++实现示例。
439

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



