判断两线段是否相交

本文搬运自本人高中时期CSDN博客,若图片加载不出来,可到原文查看:https://blog.csdn.net/zhangtingxiqwq/article/details/133943208

我们做两次

每次把一条线段视为直线,判断另一条线段的两个点是否在直线的两侧

如果两次都符合,说明直线相交

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
struct Point {
double x, y;
Point operator - (const Point &A) const {
Point B; B.x=x-A.x; B.y=y-A.y;
return B;
}
double operator ^ (const Point &A) const {
return x * A.y - y * A.x;
}
};
namespace Cross {
bool Line_cross(Point p1, Point p2, Point p3, Point p4) {
double a1 = (p1 - p2) ^ (p3 - p2);
double a2 = (p1 - p2) ^ (p4 - p2);
if(a1 * a2 >= 0) return false;
return true;
}
bool cross(Point p1, Point p2, Point p3, Point p4) {
bool t1 = Line_cross(p1, p2, p3, p4);
bool t2 = Line_cross(p3, p4, p1, p2);
return t1 && t2;
}
}