您的位置:首页 > 其它

判断两直线是否相交

2015-01-04 14:29 211 查看
#include <algorithm>
#include <iostream>
using namespace std;
#include <math.h>
#include <stdio.h>
#include <string.h>
double direction(pair<double,double> p1,pair<double,double> p2,pair<double,double> p3){
pair<double,double> d1=make_pair(p3.first-p1.first,p3.second-p1.second);
pair<double,double> d2=make_pair(p2.first-p1.first,p2.second-p1.second);
return d1.first*d2.second-d1.second*d2.first;
}

bool OnSegment(pair<double,double> p1,pair<double,double> p2,pair<double,double> p3){
double x_min,x_max,y_min,y_max;
if(p1.first<p2.first){
x_min=p1.first;
x_max=p2.first;
}else{
x_min=p2.first;
x_max=p1.first;
}
if(p1.second<p2.second){
y_min=p1.second;
y_max=p2.second;
}else{
y_min=p2.second;
y_max=p1.second;
}
if(p3.first<x_min || p3.first>x_max || p3.second<y_min || p3.second>y_max)
return false;
else
return true;
}

bool SegmentIntersect(pair<double,double> p1,pair<double,double> p2,pair<double,double> p3,pair<double,double> 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;
else if(d1==0 && OnSegment(p3,p4,p1))
return true;
else if(d2==0 && OnSegment(p3,p4,p2))
return true;
else if(d3==0 && OnSegment(p1,p2,p3))
return true;
else if(d4==0 && OnSegment(p1,p2,p4))
return true;
else
return false;
}
int main(){
double x1,y1,x2,y2,x3,y3,x4,y4;
/*cout<<"Please input x1,y1,x2,y2,x3,y3,x4,y4 by order"<<endl;*/
cin>>x1>>y1>>x2>>y2>>x3>>y3>>x4>>y4;
pair<double,double> p1=make_pair(x1,y1);
pair<double,double> p2=make_pair(x2,y2);
pair<double,double> p3=make_pair(x3,y3);
pair<double,double> p4=make_pair(x4,y4);
if(SegmentIntersect(p1,p2,p3,p4))
cout<<"Y"<<endl;
else
cout<<"N"<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: