The Wayback Machine - https://web.archive.org/web/20240823160303/https://www.geeksforgeeks.org/how-to-check-if-a-given-point-lies-inside-a-polygon/
Open In App

How to check if a given point lies inside or outside a polygon?

Last Updated : 15 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Examples:

check if a given point lies inside or outside a polygon 1

Approach: The idea to solve this problem is based on How to check if two given line segments intersect, and to be used as follows:

  1. Draw a horizontal line to the right of each point and extend it to infinity
  2. Count the number of times the line intersects with polygon edges.
  3. 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.

check if a given point lies inside or outside a polygon 2

How to handle point ‘g’ in the above figure? 

Note that we should return true if the point lies on the line or the 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 collinear with vertices of the current line of polygon. If it is collinear, 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 approach: 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
 
using namespace std;
 
struct Point {
    double x, y;
};
 
// Checking if a point is inside a polygon
bool point_in_polygon(Point point, vector<Point> polygon)
{
    int num_vertices = polygon.size();
    double x = point.x, y = point.y;
    bool inside = false;
 
    // Store the first point in the polygon and initialize
    // the second point
    Point p1 = polygon[0], p2;
 
    // Loop through each edge in the polygon
    for (int i = 1; i <= num_vertices; i++) {
        // Get the next point in the polygon
        p2 = polygon[i % num_vertices];
 
        // Check if the point is above the minimum y
        // coordinate of the edge
        if (y > min(p1.y, p2.y)) {
            // Check if the point is below the maximum y
            // coordinate of the edge
            if (y <= max(p1.y, p2.y)) {
                // Check if the point is to the left of the
                // maximum x coordinate of the edge
                if (x <= max(p1.x, p2.x)) {
                    // Calculate the x-intersection of the
                    // line connecting the point to the edge
                    double x_intersection
                        = (y - p1.y) * (p2.x - p1.x)
                              / (p2.y - p1.y)
                          + p1.x;
 
                    // Check if the point is on the same
                    // line as the edge or to the left of
                    // the x-intersection
                    if (p1.x == p2.x
                        || x <= x_intersection) {
                        // Flip the inside flag
                        inside = !inside;
                    }
                }
            }
        }
 
        // Store the current point as the first point for
        // the next iteration
        p1 = p2;
    }
 
    // Return the value of the inside flag
    return inside;
}
 
// Driver code
int main()
{
    // Define a point to test
    Point point = { 150, 85 };
 
    // Define a polygon
    vector<Point> polygon = {
        { 186, 14 }, { 186, 44 }, { 175, 115 }, { 175, 85 }
    };
 
    // Check if the point is inside the polygon
    if (point_in_polygon(point, polygon)) {
        cout << "Point is inside the polygon" << endl;
    }
    else {
        cout << "Point is outside the polygon" << endl;
    }
 
    return 0;
}


Java




import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;
 
class Point {
    double x, y;
 
    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }
}
 
public class PointInPolygon {
    // Checking if a point is inside a polygon
    public static boolean pointInPolygon(Point point, ArrayList<Point> polygon) {
        Path2D path = new Path2D.Double();
 
        // Move to the first point in the polygon
        path.moveTo(polygon.get(0).x, polygon.get(0).y);
 
        // Connect the points in the polygon
        for (int i = 1; i < polygon.size(); i++) {
            path.lineTo(polygon.get(i).x, polygon.get(i).y);
        }
 
        // Close the path
        path.closePath();
 
        // Create a Point2D object for the test point
        Point2D testPoint = new Point2D.Double(point.x, point.y);
 
        // Check if the test point is inside the polygon
        return path.contains(testPoint);
    }
 
    // Driver code
    public static void main(String[] args) {
        // Define a point to test
        Point point = new Point(150, 85);
 
        // Define a polygon
        ArrayList<Point> polygon = new ArrayList<>();
        polygon.add(new Point(186, 14));
        polygon.add(new Point(186, 44));
        polygon.add(new Point(175, 115));
        polygon.add(new Point(175, 85));
 
        // Check if the point is inside the polygon
        if (pointInPolygon(point, polygon)) {
            System.out.println("Point is inside the polygon");
        } else {
            System.out.println("Point is outside the polygon");
        }
    }
}


Python3




class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
 
# Checking if a point is inside a polygon
def point_in_polygon(point, polygon):
    num_vertices = len(polygon)
    x, y = point.x, point.y
    inside = False
 
    # Store the first point in the polygon and initialize the second point
    p1 = polygon[0]
 
    # Loop through each edge in the polygon
    for i in range(1, num_vertices + 1):
        # Get the next point in the polygon
        p2 = polygon[i % num_vertices]
 
        # Check if the point is above the minimum y coordinate of the edge
        if y > min(p1.y, p2.y):
            # Check if the point is below the maximum y coordinate of the edge
            if y <= max(p1.y, p2.y):
                # Check if the point is to the left of the maximum x coordinate of the edge
                if x <= max(p1.x, p2.x):
                    # Calculate the x-intersection of the line connecting the point to the edge
                    x_intersection = (y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y) + p1.x
 
                    # Check if the point is on the same line as the edge or to the left of the x-intersection
                    if p1.x == p2.x or x <= x_intersection:
                        # Flip the inside flag
                        inside = not inside
 
        # Store the current point as the first point for the next iteration
        p1 = p2
 
    # Return the value of the inside flag
    return inside
 
# Driver code
if __name__ == "__main__":
    # Define a point to test
    point = Point(150, 85)
 
    # Define a polygon
    polygon = [
        Point(186, 14),
        Point(186, 44),
        Point(175, 115),
        Point(175, 85)
    ]
 
    # Check if the point is inside the polygon
    if point_in_polygon(point, polygon):
        print("Point is inside the polygon")
    else:
        print("Point is outside the polygon")


C#




using System;
using System.Collections.Generic;
 
class Program
{
    // Define a structure to represent a point
    struct Point
    {
        public double x, y;
    }
 
    // Function to check if a point is inside a polygon
    static bool PointInPolygon(Point point, List<Point> polygon)
    {
        int numVertices = polygon.Count;
        double x = point.x, y = point.y;
        bool inside = false;
 
        // Store the first point in the polygon and initialize the second point
        Point p1 = polygon[0], p2;
 
        // Loop through each edge in the polygon
        for (int i = 1; i <= numVertices; i++)
        {
            // Get the next point in the polygon
            p2 = polygon[i % numVertices];
 
            // Check if the point is above the minimum y coordinate of the edge
            if (y > Math.Min(p1.y, p2.y))
            {
                // Check if the point is below the maximum y coordinate of the edge
                if (y <= Math.Max(p1.y, p2.y))
                {
                    // Check if the point is to the left of the maximum x coordinate of the edge
                    if (x <= Math.Max(p1.x, p2.x))
                    {
                        // Calculate the x-intersection of the line connecting the point to the edge
                        double xIntersection = (y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y) + p1.x;
 
                        // Check if the point is on the same line as the edge or to the left of the x-intersection
                        if (p1.x == p2.x || x <= xIntersection)
                        {
                            // Flip the inside flag
                            inside = !inside;
                        }
                    }
                }
            }
 
            // Store the current point as the first point for the next iteration
            p1 = p2;
        }
 
        // Return the value of the inside flag
        return inside;
    }
 
    // Driver code
    static void Main(string[] args)
    {
        // Define a point to test
        Point point = new Point { x = 150, y = 85 };
 
        // Define a polygon
        List<Point> polygon = new List<Point>
        {
            new Point { x = 186, y = 14 },
            new Point { x = 186, y = 44 },
            new Point { x = 175, y = 115 },
            new Point { x = 175, y = 85 }
        };
 
        // Check if the point is inside the polygon
        if (PointInPolygon(point, polygon))
        {
            Console.WriteLine("Point is inside the polygon");
        }
        else
        {
            Console.WriteLine("Point is outside the polygon");
        }
    }
}


Javascript




// JavaScript program with the same function and variable names as the C++ code
 
class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}
 
function point_in_polygon(point, polygon) {
    const num_vertices = polygon.length;
    const x = point.x;
    const y = point.y;
    let inside = false;
 
    let p1 = polygon[0];
    let p2;
 
    for (let i = 1; i <= num_vertices; i++) {
        p2 = polygon[i % num_vertices];
 
        if (y > Math.min(p1.y, p2.y)) {
            if (y <= Math.max(p1.y, p2.y)) {
                if (x <= Math.max(p1.x, p2.x)) {
                    const x_intersection = ((y - p1.y) * (p2.x - p1.x)) / (p2.y - p1.y) + p1.x;
 
                    if (p1.x === p2.x || x <= x_intersection) {
                        inside = !inside;
                    }
                }
            }
        }
 
        p1 = p2;
    }
 
    return inside;
}
 
const point = new Point(150, 85);
 
const polygon = [
    new Point(186, 14),
    new Point(186, 44),
    new Point(175, 115),
    new Point(175, 85)
];
 
if (point_in_polygon(point, polygon)) {
    console.log("Point is inside the polygon");
} else {
    console.log("Point is outside the polygon");
}


Output

Point is outside the polygon



Time Complexity: O(n) where n is the number of vertices in the given polygon.
Auxiliary Space: O(1), since no extra space has been taken.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



Previous Article
Next Article

Similar Reads

Check if the given point lies inside given N points of a Convex Polygon
Given coordinates of the N points of a Convex Polygon. The task is to check if the given point (X, Y) lies inside the polygon. Examples: Input: N = 7, Points: {(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)}, Query: X = 3, Y = 2 Below is the image of plotting of the given points: Output: YES Input: N = 7, Points: {(1, 1), (2, 1), (3, 1), (4
15 min read
Find if a point lies inside, outside or on the circumcircle of three points A, B, C
Given four non-collinear points A, B, C, and P. The task is to find whether point P lies inside, outside or on the circumcircle formed by points A, B, and C.Examples Input: A = {2, 8}, B = {2, 1}, C = {4, 5}, P = {2, 4}; Output: Point (2, 4) is inside the circumcircle. Input: A = {2, 8}, B = {2, 1}, C = {4, 5}, P = {3, 0}; Output: Point (3, 0) lies
15+ min read
Check whether a given point lies on or inside the rectangle | Set 3
Given two numbers a and b where b &lt; a form a rectangle with points (0, b), (b, 0), (a-b, b), (b, a-b). Given a point (x, y), the task is to check whether this point lies inside or on the rectangle or not. Examples: Input: a = 7, b = 2, x = 5, y = 2; Output: Given point does not lie on the rectangle Input: a = 7, b = 2, x = 4, y = 5; Output: Give
6 min read
Check whether a given point lies inside a triangle or not
Given three corner points of a triangle, and one more point P. Write a function to check whether P lies within the triangle or not. Example: Input: A = (0, 0), B = (10, 30), C = (20, 0), P(10, 15)Output: InsideExplanation: B(10,30) / \ / \ / \ / P \ P' / \ A(0,0) ----------- C(20,0) Input: A = (0, 0), B = (10, 30), C = (20, 0), P(30, 15)Output: Out
15+ min read
Check whether a given point lies inside a rectangle or not
Given four points of a rectangle, and one more point P. Write a function to check whether P lies within the given rectangle or not.Examples:   Input : R = [(10, 10), (10, -10), (-10, -10), (-10, 10)] P = (0, 0)Output : yesIllustration : Input : R = [(10, 10), (10, -10), (-10, -10), (-10, 10)], P = (20, 20)Output : noIllustration : Prerequisite: Che
14 min read
Check if a point is inside, outside or on a Hyperbola
Given a hyperbola centered at (h, k), with semi-major axis a, semi-minor axis b, both aligned with the Cartesian plane, the task is to determine if the point (x, y) lies within the area bounded by the hyperbola or not. Examples: Input: h = 0, k = 0, x = 2, y = 1, a = 4, b = 5 Output: Inside Input: h = 1, k = 2, x = 200, y = 100, a = 6, b = 5Output:
5 min read
Check if a point is inside, outside or on the ellipse
Given an ellipse centered at (h, k), with semi-major axis a, and semi-minor axis b, both aligned with the Cartesian plane. The task is to determine if the point (x, y) is within the area bounded by the ellipse. Examples:  Input: h = 0, k = 0, x = 2, y = 1, a = 4, b = 5 Output: InsideInput: h = 1, k = 2, x = 200, y = 100, a = 6, b = 5Output: Outside
10 min read
Check if a point is inside, outside or on the parabola
Given a parabola with vertex (h, k), and [Tex]a     [/Tex], the distance between focus and vertex. The task is to determine if the point (x, y) is inside, outside or on the parabola.Examples:   Input: h = 100, k = 500, x = 20, y = 10, a = 4 Output: OutsideInput: h = 0, k = 0, x = 2, y = 1, a = 4Output: Inside     Approach: It is very simple, we hav
5 min read
Check whether a point lies inside a sphere or not
Given co-ordinates of the center of a sphere (cx, cy, cz) and its radius r. Our task is to check whether a point (x, y, z) lies inside, outside or on this sphere.Examples: Input : Centre(0, 0, 0) Radius 3 Point(1, 1, 1) Output :Point is inside the sphere Input :Centre(0, 0, 0) Radius 3 Point(2, 1, 2) Output :Point lies on the sphere Input :Centre(0
7 min read
Check if a point lies inside a rectangle | Set-2
Given coordinates of bottom-left and top-right corners of a rectangle. Check if a point (x, y) lies inside this rectangle or not. Examples: Input: bottom-left: (0, 0), top-right: (10, 8), point: (1, 5) Output: Yes Input: bottom-left: (-1, 4), top-right:(2, 3), point:(0, 4) Output: No This problem is already discussed in a previous post. In this pos
6 min read
Find a point that lies inside exactly K given squares
Given an integer K and an array arr each of whose element x represents a square with two of its vertices as (0, 0) and (x, x). The task is to find a point which lies in exactly K squares. Examples: Input: arr[] = {1, 2, 3, 4}, K = 2 Output: (3, 3) The point (3, 3) lies inside 3rd and 4th square only. Input: arr[] = {8, 1, 55, 90}, K = 3 Output: (8,
3 min read
Find if a point lies inside a Circle
Given a circle (coordinates of centre and radius) and a point (coordinate), find if the point lies inside or on the circle, or not. Examples : Input: x = 4, y = 4 // Given Point circle_x = 1, circle_y = 1, rad = 6; // Circle Output: Inside Input: x = 3, y = 3 // Given Point circle_x = 0, circle_y = 1, rad = 2; // Circle Output: Outside We strongly
5 min read
Check if given point lies in range of any of the given towers
Given a 2D array arr[][] consisting of N rows of the form {Xi, Yi, Ri} such that (Xi, Yi) represents the position of a tower and Ri represents the network range of that tower. Given two integers X and Y, the task is to check if the point (X, Y) lies in the network range of the towers or not. Examples: Input: arr[][] = { {1, 1, 3}, {10, 10, 5}, {15,
7 min read
Check if a given circle lies completely inside the ring formed by two concentric circles
Given two circles of radius r and R, both have their centre at the origin. Now, given another circle of radius r1 and centre at (x1, y1). Check, if the third circle(circle of radius r1) lies completely inside the ring formed by two circles of radius r and R.Examples : Input : r = 8 R = 4 r1 = 2 x1 = 6 y1 = 0 Output : yes Input : r = 8 R = 4 r1 = 2
6 min read
Check if given polygon is a convex polygon or not
Given a 2D array point[][] with each row of the form {X, Y}, representing the co-ordinates of a polygon in either clockwise or counterclockwise sequence, the task is to check if the polygon is a convex polygon or not. If found to be true, then print "Yes" . Otherwise, print "No". In a convex polygon, all interior angles are less than or equal to 18
9 min read
Check if given point lies on the Square Spiral Path
Given a 2D Graph, present initially at (0, 0). Print "YES" if the given point (X, Y) lies on the spiral path, otherwise "NO". The spiral path is to be followed ln a sequential manner as given below: Move one unit right side from the current position.Move two units upwards from the current position.Move three units left side from the current positio
6 min read
Check whether the point (x, y) lies on a given line
Given the values of m and c for the equation of a line y = (m * x) + c, the task is to find whether the point (x, y) lies on the given line. Examples: Input: m = 3, c = 2, x = 1, y = 5 Output: Yes m * x + c = 3 * 1 + 2 = 3 + 2 = 5 which is equal to y Hence, the given point satisfies the line's equation Input: m = 5, c = 2, x = 2, y = 5 Output: No A
4 min read
Check if a circle lies inside another circle or not
Given two circles with radii and centres given. The task is to check whether the smaller circle lies inside the bigger circle or not.  Examples:   Input: x1 = 10, y1 = 8, x2 = 1, y2 = 2, r1 = 30, r2 = 10 Output: The smaller circle lies completely inside the bigger circle without touching each other at a point of circumference. Input :x1 = 7, y1 = 8
6 min read
Count points from an array that lies inside a semi-circle
Given two pairs (X, Y), (P, Q) and R the coordinate of the center of semi-circle, coordinate of the intersection of semicircle and diameter of the semicircle and, the radius of the semicircle, and an array arr[] of dimension N*2 consisting of the coordinates of few points, the task is to find the number of points from the array that lies inside or
7 min read
Count of integral coordinates that lies inside a Square
Given lower left and upper right coordinates (x1, y1) and (x2, y2) of a square, the task is to count the number of integral coordinates that lies strictly inside the square.Examples: Input: x1 = 1, y1 = 1, x2 = 5, x3 = 5 Output: 9 Explanation: Below is the square for the given coordinates: Input: x1 = 1, y1 = 1, x2 = 4, x3 = 4 Output: 4 Approach: T
4 min read
Polygon with maximum sides that can be inscribed in an N-sided regular polygon
Given a regular polygon of N sides, the task is to find the maximum sided polygon that can be inscribed inside the given polygon by joining non-adjacent vertices. Print -1, if no such polygon exist. Examples: Input: N = 8Output: 4Explanation:At most a 4 sided polygon can be inscribed inside the given 8-sided polygon as shown below: Input: N = 3Outp
3 min read
Check if vertex X lies in subgraph of vertex Y for the given Graph
Given an undirected graph and two vertices X and Y, our task is to check whether the vertex X lies in the subgraph of the vertex Y. Examples: Input: X = 2, Y = 3 Output: No Explanation: Subgraph of a vertex Y = 3 is set of all the vertex which lies below Y and are reachable by Y. Here subgraph of 3 contains {6} not 2. Input: X = 6, Y = 1 Output: Ye
10 min read
CSES Solutions - Point in Polygon
You are given a polygon of N vertices and a list of M points. Your task is to determine for each point if it is inside, outside or on the boundary of the polygon. The polygon consists of n vertices (x1,y1),(x2,y2),...,(xn,yn). The vertices (xi,yi) and (xi+1,yi+1) are adjacent for i=1,2,...,n-1, and the vertices (x1,y1) and (xn,yn) are also adjacent
10 min read
Rearrange two given arrays such that sum of same indexed elements lies within given range
Given two arrays arr1[] and arr2[] consisting of N positive integers and an even integer K, the task is to check if the sum of the same indexed elements in the two arrays lie in the range [K/2, K] after rearranging the given arrays or not. If it is possible to obtain such an arrangement, then print "Yes". Otherwise, print "No". Examples: Input: arr
6 min read
Count pairs from a given array whose product lies in a given range
Given an array arr[] of size N, and integers L and R, the task is to count the number of pairs [arri , arrj] such that i &lt; j and the product of arr[i] * arr[j] lies in the given range [L, R], i.e. L ? arr[i] * arr[j] ? R. Examples: Input: arr[ ] = {4, 1, 2, 5}, L = 4, R = 9Output: 3Explanation: Valid pairs are {4, 1}, {1, 5} and {4, 2}. Input: a
13 min read
Find time required to reach point N from point 0 according to given rules
Given two positive integers X and Y and N number of points arranged in a line, the task is to find the time required to reach point N from point 0 according to the following rules: Every point has one barrier that closes after every Y minutes and remains closed for the next Y minutes.On reaching a point if the barrier is closed, then the person nee
7 min read
Make N pairs from Array as (X, Y) coordinate point that are enclosed inside a minimum area rectangle
Given a number N, and an array A[] of size 2N, the task is to make N pairs of these array elements and place them on an X-Y coordinate plane, such that they are enclosed inside a minimum area rectangle( with sides parallel to the X-axis and Y-axis) and print the area of the rectangle. Examples: Input: N = 4, A = {1, 4, 2, 5, 3, 6, 7, 8}Output: 9Exp
7 min read
Triangle with no point inside
Given N points in 2-dimensional space, we need to find three points such that triangle made by choosing these points should not contain any other points inside. All given points will not lie on the same line so solution will always exist. Examples: In above diagram possible triangle with no point inside can be formed by choosing these triplets,[(0,
15+ min read
Find minimum radius such that atleast k point lie inside the circle
Given a positive integer K, a circle center at (0, 0) and coordinates of some points. The task is to find minimum radius of the circle so that at-least k points lie inside the circle. Output the square of the minimum radius. Examples: Input : (1, 1), (-1, -1), (1, -1), k = 3Output : 2We need a circle of radius at least 2to include 3 points.Input :
12 min read
Find intersection point of lines inside a section
Given N lines in two-dimensional space in y = mx + b form and a vertical section. We need to find out whether there is an intersection point inside the given section or not. Examples: In below diagram four lines are there, L1 : y = x + 2 L2 : y = -x + 7 L3 : y = -3 L4 : y = 2x – 7 and vertical section is given from x = 2 to x = 4 We can see that in
9 min read
three90RightbarBannerImg