给定一个多边形和一个点 ' p ',判断 ' p ' 是否位于多边形内部。位于边界上的点被视为内部。
例子:
方法:解决这个问题的思路是基于如何检查两个给定的线段是否相交,使用方法如下:
文章:
Javascript 如何检查两个给定的线段是否相交:Javascript 如何检查两个给定的线段是否相交(How to check if two given line segments intersect)_js判断两条线段是否相交-优快云博客
Java 如何检查两个给定的线段是否相交:Java 如何检查两个给定的线段是否相交(How to check if two given line segments intersect)_java判断两条线段是否相交-优快云博客
Python 如何检查两个给定的线段是否相交:Python 如何检查两个给定的线段是否相交(How to check if two given line segments intersect)_python如何判断两个线段相交-优快云博客
C# 如何检查两个给定的线段是否相交:C# 如何检查两个给定的线段是否相交(How to check if two given line segments intersect)_c# 线段交点-优快云博客
C++ 如何检查两个给定的线段是否相交:C++ 如何检查两个给定的线段是否相交(How to check if two given line segments intersect)_c++判断两条线段是否相交-优快云博客
方法:
1、在每个点的右侧画一条水平线,并延伸至无穷大
2、计算线与多边形边相交的次数。
3、如果交点数为奇数或点位于多边形的边缘,则该点位于多边形内部。如果任何条件都不成立,则该点位于多边形外部。
如何处理上图中的点‘g’?
请注意,如果点位于给定多边形的线或与给定多边形的顶点之一相同,则应返回 true。为了处理这个问题,在检查从“p”到极端的线是否相交后,我们检查“p”是否与多边形当前线的顶点共线。如果共线,则检查点“p”是否位于多边形的当前侧,如果位于,则返回 true,否则返回 false。
以下是上述方法的实现:
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")
输出:
Point is outside the polygon
时间复杂度: O(n),其中 n 是给定多边形的顶点数。
辅助空间: O(1),因为没有占用额外空间。