Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check given point in inside or boundary of given polygon or not in python
Suppose we have a list of cartesian points [(x1, y1), (x2, y2), ..., (xn, yn)] representing a polygon, and also have two values x and y. We need to check whether point (x, y) lies inside this polygon or on the boundary.
So, if the input is like points = [(0, 0), (1, 3), (4, 4), (6, 2), (4, 0)] and pt = (3, 1):
The output will be True because point (3, 1) lies inside the polygon.
Algorithm
This problem uses the ray casting algorithm. We cast a horizontal ray from the test point to the right and count how many polygon edges it crosses. If the count is odd, the point is inside; if even, it's outside.
To solve this, we follow these steps ?
- Initialize ans := False
- For each edge of the polygon:
- Get edge endpoints (x0, y0) and (x1, y1)
- Check if ray intersects this edge
- If intersection exists and is to the right of test point, toggle ans
- Return ans
Implementation
class Solution:
def solve(self, polygon, pt):
ans = False
for i in range(len(polygon)):
x0, y0 = polygon[i]
x1, y1 = polygon[(i + 1) % len(polygon)]
# Check if ray intersects this edge
if not min(y0, y1) < pt[1] <= max(y0, y1):
continue
# Skip if point is to the left of both edge endpoints
if pt[0] < min(x0, x1):
continue
# Calculate x-coordinate of intersection
cur_x = x0 if x0 == x1 else x0 + (pt[1] - y0) * (x1 - x0) / (y1 - y0)
# Toggle result if intersection is to the right of point
ans ^= pt[0] > cur_x
return ans
# Test the algorithm
ob = Solution()
points = [(0, 0), (1, 3), (4, 4), (6, 2), (4, 0)]
pt = (3, 1)
print(ob.solve(points, pt))
True
How It Works
The algorithm works by:
- Edge intersection: For each polygon edge, check if a horizontal ray from the test point intersects it
- Y-coordinate check: The ray intersects only if the test point's y-coordinate is between the edge's y-coordinates
- X-coordinate calculation: Find where the ray intersects the edge using linear interpolation
- Counting crossings: Use XOR to count odd/even intersections to the right of the test point
Testing Different Points
ob = Solution()
polygon = [(0, 0), (1, 3), (4, 4), (6, 2), (4, 0)]
test_points = [
(3, 1), # Inside
(0, 0), # On vertex
(2, 2), # Inside
(7, 3), # Outside
(1, 1) # Outside
]
for point in test_points:
result = ob.solve(polygon, point)
print(f"Point {point}: {'Inside' if result else 'Outside'}")
Point (3, 1): Inside Point (0, 0): Outside Point (2, 2): Inside Point (7, 3): Outside Point (1, 1): Outside
Conclusion
The ray casting algorithm efficiently determines if a point lies inside a polygon by counting edge crossings. This method works for any polygon shape and handles edge cases like points on vertices or boundaries.
