![]() |
VOOZH | about |
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.
Examples:
Input: N = 4, M = 3, vertices = {{1, 1}, {4, 2}, {3, 5}, {1, 4}}, points = {{2, 3}, {3, 1}, {1, 3}}
Output:
INSIDE
OUTSIDE
BOUNDARYInput: N = 4, M = 3, vertices = {{1, 3}, {1, 2}, {2, 5}, {2, 4}}, points = {{3, 3}, {1, 1}, {1, 3}}
Output:
OUTSIDE
OUTSIDE
BOUNDARY
Approach: To solve the problem, follow the below idea:
The idea is to use cross product is used to determine the orientation of three points. If the cross product is positive, the points are in counterclockwise order. If it's negative, they are in clockwise order. If it's zero, the points are collinear. We'll Sort Points by their X-coordinates to simplify the comparison process.
- Checks if a point lies on the boundary of a line segment. It does this by comparing the X-coordinates of the points and ensuring that the middle point is equal to the given point.
- Check if a point is inside or outside a polygon. Calculates the cross products of vectors formed by the polygon vertices and the point. Based on these cross products, checks for intersections and determines if the point lies on the boundary.
- Prints "INSIDE" if the point is inside the polygon, "OUTSIDE" if it's outside, and "BOUNDARY" if it lies on the boundary.
Step-by-step algorithm:
Below is the implementation of the algorithm:
INSIDE OUTSIDE BOUNDARY
Time Complexity: O(nmlog(n)), n is the number of vertices in the polygon, m is the number of points to be checked
Auxiliary Space: O(m), as it needs to store the m points in memory.