Given a polygon and a point ‘p’, find if ‘p’ lies inside the polygon or not. The points lying on the border are considered inside.
We strongly recommend to see the following post first.
How to check if two given line segments intersect?
Following is a simple idea to check whether a point is inside or outside.
1) Draw a horizontal line to the right of each point and extend it to infinity 1) Count the number of times the line intersects with polygon edges. 2) A point is inside the polygon if either count of intersections is odd or point lies on an edge of polygon. If none of the conditions is true, then point lies outside.
How to handle point ‘g’ in the above figure?
Note that we should return true if the point lies on the line or same as one of the vertices of the given polygon. To handle this, after checking if the line from ‘p’ to extreme intersects, we check whether ‘p’ is colinear with vertices of current line of polygon. If it is coliear, then we check if the point ‘p’ lies on current side of polygon, if it lies, we return true, else false.
Following is the implementation of the above idea.
No Yes Yes Yes No No
Time Complexity: O(n) where n is the number of vertices in the given polygon.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find if a point lies inside, outside or on the circumcircle of three points A, B, C
- Check if the given point lies inside given N points of a Convex Polygon
- Check if a point is inside, outside or on the ellipse
- Check if a point is inside, outside or on the parabola
- Check whether a given point lies inside a triangle or not
- Check whether a given point lies inside a rectangle or not
- Check whether a given point lies on or inside the rectangle | Set 3
- Check whether a point lies inside a sphere or not
- Check if a point lies on or inside a rectangle | Set-2
- Find a point that lies inside exactly K given squares
- Find if a point lies inside a Circle
- Check if a given circle lies completely inside the ring formed by two concentric circles
- Check if a circle lies inside another circle or not
- Check whether the point (x, y) lies on a given line
- Count of integral coordinates that lies inside a Square
- Choose points from two ranges such that no point lies in both the ranges
- Triangle with no point inside
- Find minimum radius such that atleast k point lie inside the circle
- Find intersection point of lines inside a section
- Minimum change in given value so that it lies in all given Ranges