給定2D空間中四個點的坐标 p1, p2, p3 和 p4,如果這四個點構成一個正方形,則傳回 true 。
點的坐标 pi 表示為 [xi, yi] 。輸入 不是 按任何順序給出的。
一個 有效的正方形 有四條等邊和四個等角(90度角)。
from typing import List
class Solution:
@staticmethod
def distance2(p1, p2):
return (p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2
def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
p_list = [p1,p2,p3,p4]
sorted_p_list = sorted(p_list)
if sorted_p_list[0] == sorted_p_list[1] or sorted_p_list[2] == sorted_p_list[3]:
return False
distance2s = [ self.distance2(p1, point) for point in p_list ]
# 找四條等邊
fourEqualEdge = False
fourEqualAngle = False
for point in p_list:
if point == p1 :
continue
if self.distance2(p1, point) == max(distance2s):
# point 是對點
other_points = [p for p in p_list if p != point and p != p1]
distance2s_p2 = [self.distance2(p, point) for p in other_points]
distance2s_p1 = [self.distance2(p, p1) for p in other_points]
edges = distance2s_p1
edges.extend(distance2s_p2)
#print(f"edges={edges}")
if all( x == edges[0] for x in edges):
fourEqualEdge = True
if 2*edges[0] == max(distance2s):
fourEqualAngle = True
return fourEqualEdge and fourEqualAngle
from typing import List
class Solution:
@staticmethod
def distance(point1, point2):
"""point1和point2距離的平方"""
return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2
def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
sorted_p_list = sorted([p1, p2, p3, p4])
# 如果有重複的點,則傳回False
if any(sorted_p_list[i]==sorted_p_list[i+1] for i in range(3)) :
return False
max_distance = max([self.distance(p1, point) for point in sorted_p_list])
for point in sorted_p_list:
if self.distance(p1, point) == max_distance:
# point 是對角點
other_points = [p for p in sorted_p_list if p != point and p != p1]
distance2s_p2 = [self.distance(p, point) for p in other_points]
distance2s_p1 = [self.distance(p, p1) for p in other_points]
distance2s_p1.extend(distance2s_p2)
edges = distance2s_p1
if all(x == edges[0] for x in edges) and 2 * edges[0] == max_distance:
return True
return False