[
geometry
math
]
BinarySearch 0210 Collision Detection
Problem statement
https://binarysearch.com/problems/Collision-Detection/
Solution
Let us take horizontal ray with eqution y = y0, x <= x0
and for each side find if we have intersection with this side or not. What we need to know is how many intersectoins we have: odd or even.
Complexity
It is O(n)
for time and O(1)
for space.
Code
class Solution:
def solve(self, P, x0, y0):
n, ins = len(P), 0
for i in range(n):
P1, P2 = P[i], P[(i + 1) % n]
if P1[1] > P2[1]: P1, P2 = P2, P1
if not P1[1] < y <= P2[1]: continue
if (y0 - P1[1]) * (P2[0] - P1[0]) < (x0 - P1[0]) * (P2[1] - P1[1]):
ins = 1 - ins
return bool(ins)
Remark
I am not 100 percent sure, that all border cases are considered in this solution.