# LeetCode Valid Square

LeetCode 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.

p3------p4
|       |
|       |
p1------p2

class Solution2 {
private:
// 计算距离的平方
int distSquare(const vector<int>& p1, const vector<int>& p2) {
return (p1[0] - p2[0])*(p1[0] - p2[0]) + (p1[1] - p2[1])*(p1[1] - p2[1]);
}
// 判断直线(p1,p2)和直线(p3,p4)是否垂直
bool isVertical(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
return (p2[0] - p1[0])*(p4[0] - p3[0]) + (p2[1] - p1[1])*(p4[1] - p3[1]) == 0;
}
// 在2|p1p2|==2|p1p3|==|p1p4|的条件下，判断是否能形成正方形
bool helper(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
if (!isVertical(p1, p2, p1, p3))return false;
if (!isVertical(p4, p3, p4, p2))return false;
int len2 = distSquare(p4, p2), len3 = distSquare(p4, p3);
return len2 == len3;
}
public:
bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
int len2 = distSquare(p1, p2), len3 = distSquare(p1, p3), len4 = distSquare(p1, p4);
if (len2 == 0 || len3 == 0 || len4 == 0)return false;
if (len2 == len3 && 2 * len2 == len4) return helper(p1, p2, p3, p4);
if (len2 == len4 && 2 * len2 == len3) return helper(p1, p2, p4, p3);
if (len3 == len4 && 2 * len3 == len2) return helper(p1, p3, p4, p2);
return false;
}
};

class Solution {
private:
// 计算距离的平方
int distSquare(const vector<int>& p1, const vector<int>& p2) {
return (p1[0] - p2[0])*(p1[0] - p2[0]) + (p1[1] - p2[1])*(p1[1] - p2[1]);
}
public:
bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
unordered_map<int, int> umdist;
vector<vector<int>> points = { p1,p2,p3,p4 };
for (int i = 0; i < 4; ++i) {
for (int j = i + 1; j < 4; ++j) {
int dist = distSquare(points[i], points[j]);
if (dist == 0)return false;
++umdist[dist];
}
}
return umdist.size() == 2;
}
};