【问题】
几何计算简化如下:
点(x,y) 为坐标点A,coords[x1,y1,x2,y2,x3,y3,x4,x4,…,x1,y1]为连续封闭区域坐标点。
现给定连续封闭坐标点的一维数组coords[n]和A坐标(x,y),
返回A是否在封闭图形coords内(用例不包含点在多边形边界线的情况)。
输入:
x = 1, y = 3,
coords = [0,0,0,4,4,4,2,2,4,0,0,0]
输出:true
提示
0 < coords.length < 1000
0 < coords[i] < 10000.0
0 < x < 10000.0
0 < y < 10000.0
用例保证点不会出现在多边形边界线上
Python实现:
def is_in_poly(p, poly):
"""
:param p: [x, y]
:param poly: [[], [], [], [], ...]
:return:
"""
px, py = p
is_in = False
for i, corner in enumerate(poly):
next_i = i + 1 if i + 1 < len(poly) else 0
x1, y1 = corner
x2, y2 = poly[next_i]
if (x1 == px and y1 == py) or (x2 == px and y2 == py): # if point is on vertex
is_in = True
break
if min(y1, y2) < py <= max(y1, y2): # find horizontal edges of polygon
x = x1 + (py - y1) * (x2 - x1) / (y2 - y1)
if x == px: # if point is on edge
return True
break
elif x > px: # if point is on left-side of line
is_in = not is_in
return is_in
class Solution:
def isPointInPolygon(self, x: float, y: float, coords: List[float]) -> bool:
pts = []
for i in range(len(coords) // 2):
pts.append((coords[i*2], coords[i*2+1]))
return is_in_poly((x, y), pts)
总结
可自行验证,如有误请纠正!此题未上周日顺丰竞赛题,侵权还请联系!