问题描述:
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.
示例:
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] Output: True
问题分析:
判断四个不重复的点是否能构成一个正方形,我们可以从对角线的层面出发,考虑对角线相等且平分,这就确定了四边形是个矩形,在此基础上,相邻的边相等又确定了这个矩形是正方形。
过程详见代码:
class Solution {
public:
int dis(vector<int> a, vector<int> b)
{
return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]);
}
bool mid(vector<int> a, vector<int> b, vector<int> c, vector<int> d)
{
if (a[0] + b[0] == c[0] + d[0] && a[1] + b[1] == c[1] + d[1]) return true;
return false;
}
bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
if (p1 == p2 || p1 == p3 || p1 == p4 || p2 == p3 || p2 == p4 || p3 == p4) return false;
if (dis(p1, p2) == dis(p3, p4) && mid(p1, p2, p3, p4) && dis(p1, p3) == dis(p1, p4)) return true;
if (dis(p1, p3) == dis(p2, p4) && mid(p1, p3, p2, p4) && dis(p1, p2) == dis(p1, p4)) return true;
if (dis(p1, p4) == dis(p2, p3) && mid(p1, p4, p2, p3) && dis(p1, p2) == dis(p1, p3)) return true;
return false;
}
};