问题目的:
如何判断两条线段是否相交
解决方法:
对于AB和CD两个线段可以采用所形成的点的位置来确定
- 当相交时的特点?=>ABC所形成的顺序与ABD为不一致,CDA与CDB所形成的顺序也不一致。
- 如何来描述不一致?=> 采用向量叉积来计算方向,比如ABC的方向为AB×AD的正负号决定
算法伪代码:
( order(ABC) != order(ABD) ) && ( order(CDA) != order(CDB) )
算法cpp代码:
算法代码
#include <iostream>
using namespace std;
// 定义点
struct Point2d{
double x;
double y;
// 构造
Point2d(double _x, double _y):x(_x), y(_y){}
// 定义减法
Point2d operator-(Point2d _point){
return Point2d(this->x - _point.x, this->y - _point.y);
}
};
// 定义叉乘
double cross_product(Point2d p1, Point2d p2){
return p1.x*p2.y - p1.y*p2.x;
}
// 定义判断顺序的
int order(Point2d _p1, Point2d _p2, Point2d _p3){
auto p2_sub_p1 = _p2 - _p1;
auto p3_sub_p1 = _p3 - _p1;
double res = cross_product(p2_sub_p1, p3_sub_p1);
if(res > 0) return 1;
else if(res == 0){// 特殊情况需要重新考虑
std::cout << "error" << std::endl;
}
return -1;
}
int main(){
//- 相交测试案例
线段1
// Point2d Line1_A(-1, 1);
// Point2d Line1_B(1, -1);
// // 线段2
// Point2d Line2_C(-1, -1);
// Point2d Line2_D(1, 1);
//- 非相交测试案例
// 线段1
Point2d Line1_A(0, 1);
Point2d Line1_B(0, -1);
// 线段2
Point2d Line2_C(1, -1);
Point2d Line2_D(1, 1);
if((order(Line1_A, Line1_B, Line2_C) != order(Line1_A, Line1_B, Line2_D)) &&
(order(Line2_C, Line2_D, Line1_A) != order(Line2_C, Line2_D, Line1_B))
){
std::cout << "is intersect" << std::endl;
}else{
std::cout << "no intersect" << std::endl;
}
return 0;
}