判断线段是否相交
- 快速排斥实验
- 跨立实验
介绍 :求线段是否相交
如图,判断点C和点D是否在线段AB的两侧,需要判断向量(AC)和向量(AB)的叉集 与向量(AD)和向量(AB)的叉集是否是异号的。
同理还需要判断 点AB是否在线段CD两侧
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
struct dian
{
double x,y;
};
struct xian
{
dian a;dian b;
};
//判断两条线段是否相交 首先一定要通过快速排斥试验之后 再通过跨立试验之后就能判断了这两线段相交.
bool judge(dian a,dian b,dian c,dian d)
{
//快速排斥
if(!(min(a.x,b.x)<=max(c.x,d.x) && min(c.y,d.y)<=max(a.y,b.y)&&
min(c.x,d.x)<=max(a.x,b.x) && min(a.y,b.y)<=max(c.y,d.y)))
//判断两条线段组成的矩形是否相交 如果不相交 那么这两条线是不会相交的.
//特别要注意一个矩形含于另一个矩形之内的情况
return false;
double u,v,w,z;
//定a定c.
//c.d在ab两端 a.b在cd两端.就能判断相交.
u=(c.x-a.x)*(b.y-a.y)-(b.x-a.x)*(c.y-a.y);//c.b.a//u的正负表示bc在ab的顺时针方向还是逆时针方向.
v=(d.x-a.x)*(b.y-a.y)-(b.x-a.x)*(d.y-a.y);//d.b.a//同理
w=(a.x-c.x)*(d.y-c.y)-(d.x-c.x)*(a.y-c.y);//a.d.c
z=(b.x-c.x)*(d.y-c.y)-(d.x-c.x)*(b.y-c.y);//b.d.c
return (u*v<=0.00000001 && w*z<=0.00000001);
}
int main()
{
int n;
xian str[101];
while(cin>>n && n!=0)
{
int count=0;
for(int i=0;i<n;i++)
{
cin>>str[i].a.x>>str[i].a.y>>str[i].b.x>>str[i].b.y;
}
for(int i=0;i<n;i++)//遍历所有点什么的还是比较容易理解的~.
for(int j=i+1;j<n;j++)
if(judge(str[i].a,str[i].b,str[j].a,str[j].b)) count++;
cout<<count<<endl;
}
return 0;
}
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
struct point
{
double x,y;
};
struct xian
{
point a;point b;
};
const double eps = 1e-10;
double min(double a, double b)
{
return a < b ? a : b;
}
double max(double a, double b)
{
return a > b ? a : b;
}
//判断线段ab 和线段cd相交
bool inter(point a, point b, point c, point d)
{
if (min(a.x, b.x) > max(c.x, d.x) || min(a.y, b.y) > max(c.y, d.y) || min(c.x, d.x) > max(a.x, b.x) ||
min(c.y, d.y) > max(a.y, b.y))
{
return 0;
}
double h, i, j, k;
h = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
i = (b.x - a.x) * (d.y - a.y) - (b.y - a.y) * (d.x - a.x);
j = (d.x - c.x) * (a.y - c.y) - (d.y - c.y) * (a.x - c.x);
k = (d.x - c.x) * (b.y - c.y) - (d.y - c.y) * (b.x - c.x);
return h * i <= eps && j * k <= eps;
}
int main()
{
int n;
xian str[101];
while(cin>>n && n!=0)
{
int count=0;
for(int i=0;i<n;i++)
{
cin>>str[i].a.x>>str[i].a.y>>str[i].b.x>>str[i].b.y;
}
for(int i=0;i<n;i++)//遍历所有点什么的还是比较容易理解的~.
for(int j=i+1;j<n;j++)
if(inter(str[i].a,str[i].b,str[j].a,str[j].b)) count++;
cout<<count<<endl;
}
return 0;
}