判断两条线段是否相交

思路:即利用叉积判断线段两端点是否都相互横跨

#include <iostream>


using namespace std;
struct point
{
     double x,y;
};
double min(double x,double y)
{
     return x<y?x:y;
}
double max(double x,double y)
{
     return x>y?x:y;
}
bool onsegment(point pi,point pj,point pk) //有可能在某线段上
{
     if(min(pi.x,pj.x)<=pk.x&&pk.x<=max(pi.x,pj.x))
     {
          if(min(pi.y,pj.y)<=pk.y&&pk.y<=max(pi.y,pj.y))
          {
               return true;
          }
     }
     return false;
}
double direction(point pi,point pj,point pk)//计算叉积
{
     return (pi.x-pk.x)*(pi.y-pj.y)-(pi.y-pk.y)*(pi.x-pj.x);
}
bool judge(point p1,point p2,point p3,point p4)//判断是否相交
{
     double d1 = direction(p3,p4,p1);
     double d2 = direction(p3,p4,p2);
     double d3 = direction(p1,p2,p3);
     double d4 = direction(p1,p2,p4);
     if(d1*d2<0&&d3*d4<0)
          return true;
     if(d1==0&&onsegment(p3,p4,p1))
     return true;
     if(d2==0&&onsegment(p3,p4,p2))
     return true;
     if(d3==0&&onsegment(p1,p2,p3))
     return true;
     if(d4==0&&onsegment(p1,p2,p4))
     return true;
     return false;
}
int main()
{
     point p1,p2,p3,p4;
     cin>>p1.x>>p1.y>>p2.x>>p2.y>>p3.x>>p3.y>>p4.x>>p4.y;
     if(judge(p1,p2,p3,p4))
     {
          cout<<"the two segments are interset"<<endl;
     }
     else
     {
          cout<<"the two segments are not interset"<<endl;
     }
    return 0;
}

你可能感兴趣的:(判断两条线段是否相交)