Advertisement
flash_7

Point Inside Polygon

Mar 2nd, 2017
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. /// Check whether a point lie inside a polygon.
  2. /// The polygon can be concave or convex.
  3. /// Driver function: isInside().
  4. /// Complexity: O(N).
  5.  
  6. #define inf 100000
  7.  
  8. struct Point {
  9.     int x, y;
  10. };
  11.  
  12. int orientation(Point P, Point Q, Point R){
  13.     int res = (Q.y - P.y) * (R.x - Q.x) - (Q.x - P.x) * (R.y - Q.y);
  14.     if (res > 0) return 1;
  15.     else if (res < 0) return 2;
  16.     else return 0;
  17. }
  18.  
  19. bool onSegment(Point P, Point Q, Point R){
  20.     if (R.x >= min(P.x, Q.x) && R.x <= max(P.x, Q.x) && R.y >= min(P.y, Q.y)
  21.             && R.y <= max(P.y, Q.y)){
  22.         return true;
  23.     }else{
  24.         return false;
  25.     }
  26. }
  27.  
  28. bool doIntersect(Point P1, Point P2, Point P3, Point P4, bool &onLine){
  29.     int o1 = orientation(P1, P2, P3);
  30.     int o2 = orientation(P1, P2, P4);
  31.     int o3 = orientation(P3, P4, P1);
  32.     int o4 = orientation(P3, P4, P2);
  33.  
  34.     if (o1 != o2 && o3 != o4 && o1 != 0 && o2 != 0 && o3 != 0 && o4 != 0){
  35.         return true;
  36.     }
  37.  
  38.     if (o1 == 0 && onSegment(P1, P2, P3)){
  39.         onLine = true;
  40.         return true;
  41.     }
  42.  
  43.     if (o2 == 0 && onSegment(P1, P2, P4)) return true;
  44.     if (o3 == 0 && onSegment(P3, P4, P1)) return true;
  45.     if (o4 == 0 && onSegment(P3, P4, P2)) return true;
  46.     return false;
  47. }
  48.  
  49. bool isInside(Point P, vector<Point> &List) {
  50.     Point Q;
  51.     Q.y = P.y + inf;
  52.     Q.x = P.x + inf + 1;
  53.     bool onLine = false; /// To check if the point lie on any segment
  54.     int cnt = 0;
  55.     for (int i = 0; i + 1 < List.size(); i++){
  56.         if (doIntersect(List[i], List[i + 1], P, Q, onLine)) cnt++;
  57.     }
  58.     if (onLine) return true;
  59.     if (cnt % 2 == 1) return true;
  60.     return false;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement