判斷線段是否與矩形相交

輸入格式:

xstart ystart xend yend xleft ytop xright ybottom
Note: The terms top left and bottom right do not imply any ordering of coordinates.


計算幾何題對我來說,光是寫對就要花很久,而代碼還要做到既簡潔又易懂真是難上加難……
注意點在於:線段與矩形不相交,這意味着線段不僅可以在矩形外,還可以在矩形內。

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int t, x1, y1, x2, y2, xl, yt, xr, yb;
    int a, b, c, f1, f2, f3, f4;
    cin >> t;
    while (t--)
    {
        scanf("%d%d%d%d%d%d%d%d", &x1, &y1, &x2, &y2, &xl, &yt, &xr, &yb);
        if (xl > xr) swap(xl, xr);
        if (yt < yb) swap(yt, yb);
        a = y1 - y2;
        b = x2 - x1;
        c = x1 * y2 - y1 * x2;
        f1 = a * xl + b * yb + c;
        f2 = a * xl + b * yt + c;
        f3 = a * xr + b * yb + c;
        f4 = a * xr + b * yt + c;
        if ((f1>0 && f2>0 && f3>0 && f4>0) || (f1<0 && f2<0 && f3<0 && f4<0))
            printf("F\n");
        else if ((x1 > xr && x2 > xr) || (x1 < xl && x2 < xl))
            printf("F\n");
        else if ((y1 > yt && y2 > yt) || (y1 < yb && y2 < yb))
            printf("F\n");
        else
            printf("T\n");
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章