题目描述
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.
题意:给定二维空间中四点的坐标,返回四点是否可以构造一个正方形。
一个点的坐标(x,y)
由一个有两个整数的整数数组表示。
算法1
题解:判断空间中的四个点是否是正方形:
- 四个顶点总共有六条边,那么有四条边相等且不为0(菱形)
- 对角线相等的菱形是正方形。
bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
int p12 = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]);
int p23 = (p3[0] - p2[0]) * (p3[0] - p2[0]) + (p3[1] - p2[1]) * (p3[1] - p2[1]);
int p34 = (p3[0] - p4[0]) * (p3[0] - p4[0]) + (p3[1] - p4[1]) * (p3[1] - p4[1]);
int p41 = (p1[0] - p4[0]) * (p1[0] - p4[0]) + (p1[1] - p4[1]) * (p1[1] - p4[1]);
int p13 = (p1[0] - p3[0]) * (p1[0] - p3[0]) + (p1[1] - p3[1]) * (p1[1] - p3[1]);
int p24 = (p2[0] - p4[0]) * (p2[0] - p4[0]) + (p2[1] - p4[1]) * (p2[1] - p4[1]);
if(p12 == 0 || p23 == 0 || p34 == 0 || p41 == 0 || p13 == 0 || p24 == 0)
return false;
if((p12 == p13 && p24 == p34 && p12 == p24 && p41 == p23) || (p12 == p41 && p41 == p34 && p23 == p34 && p13 == p24) || (p13 == p41 && p23 == p24 && p13 == p23 && p12 == p34))
return true;
return false;
}