其他分享
首页 > 其他分享> > 【模板】计几 射线法判断点是否在简单多边形内

【模板】计几 射线法判断点是否在简单多边形内

作者:互联网

 1 //
 2 //线段交点个数
 3 int SegCross(Segment a,Segment b){
 4     double x1 = a.s.cross(a.e,b.s);
 5     double x2 = a.s.cross(a.e,b.e);
 6     double x3 = b.s.cross(b.e,a.s);
 7     double x4 = b.s.cross(b.e,a.e);
 8     if( b.e.OnLine(a.s,a.e) && b.s.OnSeg(a.s,a.e) ||
 9         b.s.OnLine(a.s,a.e) && b.e.OnSeg(a.s,a.e) ||
10         a.e.OnLine(b.s,b.e) && a.s.OnSeg(b.s,b.e) ||
11         a.s.OnLine(b.s,b.e) && a.e.OnSeg(b.s,b.e) )
12         return 2;
13     else if(sgn(x1*x2) <= 0 && sgn(x3*x4)<=0) return 1;
14     return 0;
15 
16 }
17  
18 ///判断点p0与含有n个节点的多边形的位置关系
19 //p数组是顶点集合; 射线法判断点和多边形位置关系,多边形的点要求必须是逆时针描述. 
20 ///返回0:边上或顶点上,    1:外面,   -1:里面;
21 //节点从0到n-1
22 int PointInPolygon(Point p0, Point p[], int n)
23 {
24     Segment L, S;
25     Point temh,teml;
26     L.s = p0, L.e = Point(inf, p0.y);///以p0为起点的射线L;
27  
28     int counts = 0;
29     p[n] = p[0];
30  
31     for(int i=1; i<=n; i++)
32     {
33         S.s = p[i-1], S.e = p[i];
34  
35         if(p0.OnSeg(S.s,S.e) ) return 0;
36         if(S.s.y == S.e.y) continue;///和射线平行;
37  
38         if(S.s.y > S.e.y) temh = S.s,teml = S.e;
39         else temh = S.e,teml = S.s;
40  
41         if(temh.OnSeg(L.s,L.e) )
42             counts ++;
43         else if(SegCross(L, S) == 1 && teml.OnSeg(L.s,L.e) == 0)
44             counts ++;
45     }
46     if(counts%2) return -1;
47     return 1;
48 }
View Code

 

标签:计几,OnSeg,多边形,double,cross,&&,OnLine,return,模板
来源: https://www.cnblogs.com/xiaobuxie/p/11771620.html