UVA 191 || Intersection (判断线段是否与矩形相交

写这实在太烦了。。贴模板。。所以感觉不算原创 = =


1)。线段包含与矩形内也算相交。先判断是否在矩形内

然后照着这个博客走就行了。

理论: http://dev.gameres.com/Program/Abstract/Geometry.htm#判断两线段是否相交

代码:http://blog.csdn.net/mobius_strip/article/details/8373558

#include 
#include 
#include 
#include 

#define min(x,y) ((x)<(y)?(x):(y))
#define max(x,y) ((x)>(y)?(x):(y))

//点结构
typedef struct pnode
{
    double x,y;
    pnode( double a, double b ){x = a;y = b;}
    pnode(){}
}point;

//线结构
typedef struct lnode
{
    double x,y,dx,dy;
    lnode( point a, point b ){x = a.x;y = a.y;dx = b.x-a.x;dy = b.y-a.y;}
    lnode(){}
}line;

//点在矩形内判断
bool in( point p, point a, point b )
{
	return (a.x <= p.x)&&(a.y >= p.y)&&(b.x >= p.x)&&(b.y <= p.y);
}


//线段相交
bool cross( line a, line b )
{
    double t1 = a.dx*(b.y-a.y)-a.dy*(b.x-a.x);
    double t2 = a.dx*(b.y+b.dy-a.y)-a.dy*(b.x+b.dx-a.x);
    double t3 = b.dx*(a.y-b.y)-b.dy*(a.x-b.x);
    double t4 = b.dx*(a.y+a.dy-b.y)-b.dy*(a.x+a.dx-b.x);
    if ( t1*t2 == 0 && t3*t4 == 0 ) {
            /*当 ( P1 - Q1 ) × ( Q2 - Q1 ) = 0 时,说明 ( P1 - Q1 ) 和 ( Q2 - Q1 )共线,
            但是因为已经通过快速排斥试验,所以 P1 一定在线段 Q1Q2上;*/
		point A = point( a.x, a.y );
		point B = point( a.x+a.dx, a.y+a.dy );
		point C = point( b.x, b.y );
		point D = point( b.x+b.dx, b.y+b.dy );
		point E = point( min( A.x, B.x ), max( A.y, B.y ) );
		point F = point( max( A.x, B.x ), min( A.y, B.y ) );
		if ( in( A, C, D ) || in( B, C, D ) || in( C, E, F ) || in( D, E, F ) )
			return 1;
		else return 0;
	}
    return (t1*t2 < 0)&&(t3*t4 < 0);
    /* 如果两线段相交,则两线段必然相互跨立对方。
        若P1P2跨立Q1Q2 ,则矢量 ( P1 - Q1 ) 和( P2 - Q1 )位于矢量( Q2 - Q1 ) 的两侧,
        即( P1 - Q1 ) × ( Q2 - Q1 ) * ( P2 - Q1 ) × ( Q2 - Q1 ) < 0。
    */
}

int main()
{
	int    n;
	point  a,b,c,d,e,f;
	while ( scanf("%d",&n) != EOF )
	while ( n -- ) {
		scanf("%lf%lf%lf%lf",&a.x,&a.y,&b.x,&b.y);
		scanf("%lf%lf%lf%lf",&e.x,&e.y,&f.x,&f.y);
		c = point( min( e.x, f.x ), max( e.y, f.y ) );
		d = point( max( e.x, f.x ), min( e.y, f.y ) );
		line ll = line( a, b );
		line l1 = line( c, point(c.x,d.y) );
		line l2 = line( point(c.x,d.y), d );
		line l3 = line( c, point(d.x,c.y) );
		line l4 = line( point(d.x,c.y), d );
		if ( in( a, c, d ) || in( b, c, d ) )
			printf("T\n");
		else if ( cross( ll, l1 ) || cross( ll ,l2 ) || cross( ll, l3 ) || cross( ll, l4 ) )
			printf("T\n");
		else printf("F\n");
	}
	return 0;
}



你可能感兴趣的:(计算几何)