题目描述
解法:线代(Python)
想问此题怎么做,看你线代学的怎么样
详细参考 terjer7的解
class Solution:
def intersection(self, start1: List[int], end1: List[int], start2: List[int], end2: List[int]) -> List[float]:
x1, y1, x2, y2, x3, y3, x4, y4 = *start1, *end1, *start2, *end2
det = lambda a, b, c, d: a * d - b * c
d = det(x1 - x2, x4 - x3, y1- y2, y4 - y3)
p = det(x4 - x2, x4 - x3, y4 - y2, y4 - y3)
q = det(x1 - x2, x4 - x2, y1 - y2, y4 - y2)
if d:
lam, eta = p / d, q / d
if not(0 <= lam <= 1 and 0 <= eta <= 1):
return []
return [lam * x1 + (1 - lam) * x2, lam * y1 + (1 - lam) * y2]
elif p or q:
return []
t1, t2 = sorted([start1, end1]), sorted([start2, end2])
if t1[1] < t2[0] or t2[1] < t1[0]: return []
return max(t1[0], t2[0])