Point in Polygon problem is a classic computational geometry problem where the task is to determine whether a given point lies inside, outside, or on the boundary of a polygon, the point that lies on the border is considered as inside only.
In this article, we will learn how to check if a given point lies inside or outside a polygon. We will also look at different methods to achieve this.
Example:
Input:
Polygon: {{1, 1}, {1, 5}, {5, 5}, {5, 1}}
Point: {3, 3}
Output:
Point is inside the polygon.
Point in PolygonHow to Check if a Point Lies Inside or Outside a Polygon?
Checking if a point lies inside a polygon involves determining the relative position of the point concerning the polygon's edges. There are several methods to achieve this in C++.
Method 1: Using Ray-Casting Algorithm
In this method, we draw a horizontal ray from the point to the outside of the polygon and count how many times the ray intersects the polygon's edges. If the number of intersections is odd, the point is inside the polygon; if even, it is outside.
Point in PolygonApproach
- Initialize a count to zero to keep track of the number of times a ray cast from the point intersects with the polygon's edges.
- Start iterating through each edge of the polygon:
- Check if the point's y-coordinate lies within the y-range of the current edge.
- Determine the x-coordinate where the ray intersects with the edge using linear interpolation if applicable.
- Count intersections where the ray crosses from left to right.
- If the number of intersections is odd, the point is inside the polygon. Otherwise, the point is outside.
C++ Program to Check Point in Polygon using Ray-Casting Algorithm
The below program demonstrates how we can check if a point lies inside or outside a polygon using Ray-Casting Algorithm in C++.
C++
// C++ program to check if a point lies inside or outside a
// polygon using Ray-Casting Algorithm
#include <iostream>
#include <vector>
using namespace std;
struct Point {
// Coordinates of the point
double x, y;
};
// Function to check if a point is inside a polygon using
// the ray-casting algorithm
bool isPointInPolygon(const vector<Point>& polygon,
const Point& point)
{
// Number of vertices in the polygon
int n = polygon.size();
// Count of intersections
int count = 0;
// Iterate through each edge of the polygon
for (int i = 0; i < n; i++) {
Point p1 = polygon[i];
// Ensure the last point connects to the first point
Point p2 = polygon[(i + 1) % n];
// Check if the point's y-coordinate is within the
// edge's y-range and if the point is to the left of
// the edge
if ((point.y > min(p1.y, p2.y))
&& (point.y <= max(p1.y, p2.y))
&& (point.x <= max(p1.x, p2.x))) {
// Calculate the x-coordinate of the
// intersection of the edge with a horizontal
// line through the point
double xIntersect = (point.y - p1.y)
* (p2.x - p1.x)
/ (p2.y - p1.y)
+ p1.x;
// If the edge is vertical or the point's
// x-coordinate is less than or equal to the
// intersection x-coordinate, increment count
if (p1.x == p2.x || point.x <= xIntersect) {
count++;
}
}
}
// If the number of intersections is odd, the point is
// inside the polygon
return count % 2 == 1;
}
int main()
{
vector<Point> polygon
= { { 1, 1 }, { 1, 5 }, { 5, 5 }, { 5, 1 } };
// Define a polygon
Point point = { 3, 3 }; // Define a point to check
// Check if the point is inside the polygon and print
// the result
if (isPointInPolygon(polygon, point)) {
cout << "Point is inside the polygon." << endl;
}
else {
cout << "Point is outside the polygon." << endl;
}
return 0;
}
OutputPoint is inside the polygon.
Time Complexity: O(n), where n is the number of vertices in the polygon.
Auxiliary Space: O(1)
Method 2: Using Winding Number Algorithm
The Winding Number algorithm counts the number of times the polygon winds around the point. If the winding number is non-zero, the point is inside; otherwise, it is outside. This method is robust and handles complex polygons, including those with holes.
Approach
- Initialize a winding number to zero to count how many times the polygon winds around the point.
- Start iterating through each edge of the polygon:
- Check if the point lies on the current edge of the polygon.
- Determine the relative position of the point to the current edge using cross product to determine if the polygon winds around the point.
- If the winding number is non-zero, the point is inside the polygon and if the winding number is zero, the point is outside.
C++ Program to Check Point in Polygon using Winding Number Algorithm
The below program demonstrates how we can check if a point lies inside or outside a polygon using Winding Number Algorithm in C++.
C++
// C++ program to check if a point lies inside or outside a
// polygon using Winding Number Algorithm
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
struct Point {
double x, y;
};
// Function to compute the cross product of vectors (p1p2)
// and (p1p3)
double crossProduct(const Point& p1, const Point& p2,
const Point& p3)
{
return (p2.x - p1.x) * (p3.y - p1.y)
- (p2.y - p1.y) * (p3.x - p1.x);
}
// Function to check if point p lies on segment p1p2
bool isPointOnSegment(const Point& p, const Point& p1,
const Point& p2)
{
// Check if point p lies on the line segment p1p2 and
// within the bounding box of p1p2
return crossProduct(p1, p2, p) == 0
&& p.x >= min(p1.x, p2.x)
&& p.x <= max(p1.x, p2.x)
&& p.y >= min(p1.y, p2.y)
&& p.y <= max(p1.y, p2.y);
}
// Function to compute the winding number of a point with
// respect to a polygon
int windingNumber(const vector<Point>& polygon,
const Point& point)
{
int n = polygon.size();
int windingNumber = 0;
// Iterate through each edge of the polygon
for (int i = 0; i < n; i++) {
Point p1 = polygon[i];
// Next vertex in the polygon
Point p2 = polygon[(i + 1) % n];
// Check if the point lies on the current edge
if (isPointOnSegment(point, p1, p2)) {
// Point is on the polygon boundary
return 0;
}
// Calculate the cross product to determine winding
// direction
if (p1.y <= point.y) {
if (p2.y > point.y
&& crossProduct(p1, p2, point) > 0) {
windingNumber++;
}
}
else {
if (p2.y <= point.y
&& crossProduct(p1, p2, point) < 0) {
windingNumber--;
}
}
}
// Return the winding number
return windingNumber;
}
// Function to check if a point is inside a polygon using
// the winding number algorithm
bool isPointInPolygon(const vector<Point>& polygon,
const Point& point)
{
// Compute the winding number for the point with respect
// to the polygon
return windingNumber(polygon, point) != 0;
}
int main()
{
// Define a polygon
vector<Point> polygon
= { { 1, 1 }, { 1, 5 }, { 5, 5 }, { 5, 1 } };
// Define a point to check
Point point = { 3, 3 };
// Check if the point is inside the polygon using the
// winding number algorithm
if (isPointInPolygon(polygon, point)) {
cout << "Point is inside the polygon." << endl;
}
else {
cout << "Point is outside the polygon." << endl;
}
return 0;
}
Time Complexity: O(n), where n is the number of vertices in the polygon.
Auxiliary Space: O(1)
Method 3: Using Crossing Number Algorithm
The Crossing Number algorithm is similar to the Ray-Casting algorithm but uses a vertical ray instead. It counts the number of times the vertical ray from the point intersects the polygon's edges. If the count is odd, the point is inside; if even, it is outside.
Approach
- Initialize a boolean variable inside to false to keep a track whether the point is inside the polygon based on the number of edge crossings.
- Start iterating through each edge of the polygon:
- Determine if the point lies on the same side of the edge's y-range as the polygon.
- Count edge crossings from one side to the other using linear interpolation to find the x-coordinate where the ray crosses the edge.
- If the number of crossings is odd, toggle the inside variable to true and if the number of crossings is even, the point remains outside the polygon.
C++ Program to Check Point in Polygon using Crossing Number Algorithm
The below program demonstrates how we can check if a point lies inside or outside a polygon using Winding Number Algorithm in C++.
C++
// C++ program to Check Point in Polygon using Crossing
// Number Algorithm
#include <iostream>
#include <vector>
using namespace std;
struct Point {
double x, y;
};
// Function to check if a point is inside a polygon using
// the ray-casting algorithm
bool isPointInPolygon(const vector<Point>& polygon,
const Point& point)
{
int n = polygon.size();
bool inside = false;
// Iterate through each edge of the polygon
for (int i = 0; i < n; i++) {
Point p1 = polygon[i];
// Next vertex in the polygon
Point p2 = polygon[(i + 1) % n];
// Check if the point is between the y-coordinates
// of p1 and p2
bool yCheck = (p1.y > point.y) != (p2.y > point.y);
// Calculate the x-coordinate where the ray from the
// point intersects the edge
double xIntersect = (p2.x - p1.x) * (point.y - p1.y)
/ (p2.y - p1.y)
+ p1.x;
// Check if the point lies to the left of the
// intersection
if (yCheck && point.x < xIntersect) {
// Toggle inside flag
inside = !inside;
}
}
// Return true if point is inside the polygon, false
// otherwise
return inside;
}
int main()
{
// Define a polygon
vector<Point> polygon
= { { 1, 1 }, { 1, 5 }, { 5, 5 }, { 5, 1 } };
// Define a point to check
Point point = { 3, 3 };
// Check if the point is inside the polygon using the
// ray-casting algorithm
if (isPointInPolygon(polygon, point)) {
cout << "Point is inside the polygon." << endl;
}
else {
cout << "Point is outside the polygon." << endl;
}
return 0;
}
Time Complexity: O(n), where n is the number of vertices in the polygon.
Auxiliary Space: O(1)
Conclusion
Determining if a point lies inside a polygon is a fundamental operation in computational geometry. We have explored three different methods to check if a point is inside a polygon in C++: using the Ray-Casting Algorithm, the Winding Number Algorithm, and the Crossing Number Algorithm. Each method has its own strengths and can be chosen based on the specific requirements of the application.
Similar Reads
Point in Polygon in C In computational geometry, we come across a problem to determine whether a given point lies inside, outside, or on the boundary of a polygon. This problem, known as the "Point in Polygon" (PIP) problem. It has numerous applications in computer graphics, geographic information systems (GIS), and robo
12 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
10 min read
Convex Polygon Convex polygons are special shapes with straight sides that don't fold inward. All the lines connecting the corners of a convex polygon stay inside the shape. The corners of a convex polygon always point outward. A regular polygon, where all sides and angles are equal, is always convex. If a closed
8 min read
Rotation of a point about another point We have already discussed the rotation of a point P about the origin in the Set 1 and Set 2. The rotation of point P about origin with an angle ? in the anti-clockwise direction is given as under: Rotation of P about origin: P * polar(1.0, ?)Rotation of P about point Q Now, we have to rotate the poi
8 min read
Polygon Formula - Definition, Symbol, Examples Polygons are closed two-dimensional shapes made with three or more lines, where each line intersects at vertices. Polygons can have various numbers of sides, such as three (triangles), four (quadrilaterals), and more. In this article, we will learn about the polygon definition, the characteristics o
7 min read