两个矩形的相交区域

时间:2019-03-02 00:21:12

标签: 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轴获得正确的重叠。

1 个答案:

答案 0 :(得分:3)

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