今天沒有開頭,直接進入正題
Given the coordinates of four points in 2D space, return whether the four points could construct a square.
The coordinate (x,y) of a point is represented by an integer array with two integers.
Example:
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: True
Note:
All the input integers are in the range [-10000, 10000].
A valid square has four equal sides with positive length and four equal angles (90-degree angles).
Input points have no order.
我想到的方法是,把p1想成固定的起始點,一個個和另外三個點比,找看有沒有x座標或y座標有相同的作為下個點;
找到第二個點之後,再和另外兩個點相比確認,依序確認成正方形
但是這樣程式碼的判斷會很多很冗長,而且無法判斷出兩邊不是平行於X軸和Y軸的正方形
正好跟我爸討論了下,想到可以檢查任兩點的距離是否為A或根號2倍A
這樣程式碼應該像這樣:
def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
Ip1p2 = distance(p1,p2)
Jp1p3 = distance(p1,p3)
Kp1p4 = distance(p1,p4)
if (Ip1p2 == Jp1p3 and Ip1p2 == pow(Kp1p4, 0.5)) or (Ip1p2 == Jp1p3 and Jp1p3 == pow(Kp1p4, 0.5)) or (Jp1p2 == Kp1p3 and Jp1p3 == pow(Ip1p4, 0.5)):
return True
else:
return False
def distance(self, A:List[int], B:List[int]) -> float:
dist = pow((pow((A[0]-B[0]), 2) + pow((A[1]-B[1]), 2), 0.5)
if ((A[0]-B[0])<0) or ((A[1]-B[1])<0):
return (0 - dist)
else:
return dist
結果在這行
if ((A[0]-B[0])<0) or ((A[1]-B[1])<0):
出現了語法錯誤,明天繼續