## 题目描述：

LeetCode 593. Valid Square

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:

1. All the input integers are in the range [-10000, 10000].
2. A valid square has four equal sides with positive length and four equal angles (90-degree angles).
3. Input points have no order.

## 题目大意：

1. 坐标的范围[-10000, 10000]
2. 有效的正方形有4条相等的长度为正数的边，并且四个内角为直角。
3. 输入点无序

## 解题思路：

```记4个点中最左下方的点为lb

## Python代码：

``````class Solution(object):
def validSquare(self, p1, p2, p3, p4):
"""
:type p1: List[int]
:type p2: List[int]
:type p3: List[int]
:type p4: List[int]
:rtype: bool
"""
pts = [p1, p2, p3, p4]
lb = min(pts)
ccw = lambda p1, p2, p3: (p2[0] - p1[0]) * (p3[1] - p1[1]) - (p2[1] - p1[1]) * (p3[0] - p1[0])
dsquare = lambda p1, p2: (p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2
cmp = lambda p, q: ccw(lb, q, p) or dsquare(p, lb) - dsquare(q, lb)
pts.sort(cmp)
if not all(dsquare(pts[i], pts[j]) for i, j in zip((0, 1, 2, 3), (1, 2, 3, 0))): return False
if len(set(dsquare(pts[i], pts[j]) for i, j in zip((0, 1, 2, 3), (1, 2, 3, 0)))) > 1: return False
return dsquare(pts[0], pts[1]) * 2 == dsquare(pts[0], pts[2])
``````

Pingbacks已关闭。