射线法,用来判断点在多边形的内外,适用于任意多边形
时间复杂度:O(n)
从该点引出一条水平射线,观察射线与多变形的交点个数.
当射线与多边形的交点个数是奇数时,P在多边形内; 偶数时,P在多边形外。
我们通常将射线设为水平向右(哪个方向都可以,只是水平容易写一点而已)
图一这种情况计两次或者不计都可
图二这种情况只计一次
图三这种情况也是计两次或者不计都可
最后,根据点数判断点P在多边形内外。
注意:点必须有顺序,顺时针或逆时针
代码:
你品,你仔细品(逃
const double EPS=1e-9;
inline int sgn(double a){ return a < -EPS ? -1 : a > EPS; }
inline int cmp(double a, double b){ return sgn(a-b); }
struct Point;
struct Line;
typedef Point Vector;
struct Point{
double x,y;
Point(){}
Point(double a, double b):x(a),y(b){}
double len(){return sqrt(x*x+y*y);}
bool onSegment(Line l);
int inPolygon(Point poly[]);
void read(){scanf("%lf%lf",&x,&y);}
Point operator+(Vector v){return {x+v.x,y+v.y};}
Vector operator-(Point p){return {x-p.x,y-p.y};}
double operator^(Vector v){return x*v.y-y*v.x;}//叉乘
double operator*(Vector v){return x*v.x+y*v.y;}//点乘
};
bool Point::onSegment(Line l){
Vector v1=l.s-*this;
Vector v2=l.e-*this;
return sgn(v1^v2)==0&&sgn(v1*v2)<=0;
}
int Point::inPolygon(Point poly[]){//判断点是否在多边形内,若点在多边形内返回1,在多边形外部返回0,在多边形上返回-1
int wn = 0;
for(int i = 1; i <= n; ++i){
if(onSegment({poly[i], poly[i%n+1]})) return -1;
int k = sgn((poly[i%n+1] - poly[i])^(*this - poly[i]));
int d1 = sgn(poly[i].y - y);
int d2 = sgn(poly[i%n+1].y - y);
if(k > 0 && d1 <= 0 && d2 > 0) wn++;
if(k < 0 && d2 <= 0 && d1 > 0) wn++;
}
return wn%2;
}