c++ - 两个矩形的交集面积

标签 c++ algorithm

我遇到了这段有趣的代码。它计算两个矩形的重叠面积。

#include <iostream>
using namespace std;


int overlapLine(int p11, int p12, int p21, int p22)
{
    int buf;

    buf = p11;
    p11 = min(p11, p12);
    p12 = max(buf, p12);

    buf = p21;
    p21 = min(p21, p22);
    p22 = max(buf, p22);

    return  max(0, max(0, p12 - p21) - max(0, p11 - p21) - max(0, p12 - p22));
}


int main(int argc, char* argv[])
{
    int x11 = -5, y11 = -5, x12 = 5,  y12 = 5;
    int x21 = -1, y21 = -1, x22 = 1,  y22 = 1;

    int w = overlapLine(x11, x12, x21, x22);
    int h = overlapLine(y11, y12, y21, y22);

    int overlapArea = w * h;
    cout << "OVERLAP AREA: " << overlapArea << endl;

    return 0;
}

代码有效并产生正确的结果。但是,我无法理解 overlapLine 如何通过 X 轴和 Y 轴获得正确的重叠。

最佳答案

希望这能回答您的问题: enter image description here

关于c++ - 两个矩形的交集面积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54954012/

相关文章:

c++ - vector 填充不同的对象

c++ - zlib compress2 返回 Z_STREAM_ERROR

c - 为什么我的字符串到 float 的转换函数返回的数字在纯 C 中略有偏差?

algorithm - 合并多个排序数组的分而治之策略

c++ - 一个 C++ 函数,用于计算和采样射弹在 3D 空间中的轨迹。物理编程

c++ - "Recursive on All Control Paths"执行阶乘函数时出错

c++自定义字符串格式使用stringstreams

java - 模式的字符串匹配

python - O(n) + O(n) = O(n)?

java - 提高反转数组的性能