判断两条线段是否相交

根据这个性质可以判断点p2是在线段的左边还是右边,这是判断两条线段是否相交的一个重要性质。

 这是判断两条线段相交的一种情况,一条线段的端点在另一条线段上。

这是判断两条线段是否相交的原理。

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cmath>
 4 using namespace std;
 5 
 6 struct point {
 7     double x, y;
 8 };
 9 
10 bool segmentsIntersect(point p1, point p2, point p3,point p4) {
11     double d1 = direction(p1, p2, p3);
12     double d2 = direction(p1, p2, p4);
13     double d3 = direction(p3, p4, p1);
14     double d4 = direction(p3, p4, p2);
15 
16     if (d1 > 0 && d2 < 0 || d1 < 0 || d2>0 || d3>0 && d4 < 0 || d3 < 0 && d4>0)
17         return true;
18     if (fabs(d1) <= 1e-9 && onSegment(p1, p2, p3)) return true;
19     if (fabs(d2) <= 1e-9 && onSegment(p1, p2, p4)) return true;
20     if (fabs(d3) <= 1e-9 && onSegment(p3, p4, p1)) return true;
21     if (fabs(d4) <= 1e-9 && onSegment(p3, p4, p2)) return true;
22     return false;
23 }
24 
25 //这是判断p3是在线段p1p2的哪一侧
26 double direction(point p1, point p2, point p3) {
27     return (p2.x - p1.x)*(p3.y - p2.y) - (p3.x - p2.x)*(p2.y - p1.y);
28 }
29 
30 //这是判断点p3是否在以p1p2为对角线的矩形内
31 bool onSegment(point p1, point p2, point p3) {
32     if (p3.x >= min(p1.x, p2.x) && p3.x <= max(p1.x, p2.x) &&
33         p3.y >= min(p1.y, p2.y) && p3.y <= max(p1.y, p2.y))
34         return true;
35     return false;
36 }

下面还有一种详情可以看算法导论的几何篇

这个方法略懂。

自己选的路,跪着也要把它走完------ACM坑
原文地址:https://www.cnblogs.com/IKnowYou0/p/6058593.html