题目:
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.
思路:
首先复习一下如何判定一个四边形是正方形:1)两对对边平行且相等的四边形是平行四边形;2)有一个内角为90°的平行四边形是矩形;3)临边相等的矩形是正方形。
具体到这道题目,我们首先判断由p1, p2, p3, p4顺次构成的四边形是否是平行四边形(通过判断两个对边构成的向量是否相等实现),然后判断是否是长方形(通过判断相邻的边构成的两个向量的内积是否为0来实现);最后判断是否是正方形(通过判断相邻边的边长是否相等来实现)。
由于题目中给出的p1, p2, p3, p4是无序的,所以我们需要分别判断(p1, p2, p3, p4), (p1, p2, p4, p3)和(p1, p3, p2, p4)顺次相连是否可以构成正方形。只要有一个可以构成,就返回true。
代码:
class Solution {
public:
bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
if (isValid(p1, p2, p3, p4)) { // check whether p1, p2, p3, p4 could form the square
return true;
}
if (isValid(p1, p3, p2, p4)) { // check whether p1, p3, p2, p4 could form the square
return true;
}
if (isValid(p1, p2, p4, p3)) { // check whether p1, p2, p4, p3 could form the square
return true;
}
return false;
}
private:
int dotProduct(vector<int> &v1, vector<int> &v2) {
return v1[0] * v2[0] + v1[1] * v2[1];
}
int squaredLength(vector<int> &v) {
return dotProduct(v, v);
}
bool isValid(vector<int> &p1, vector<int> &p2, vector<int> &p3, vector<int> &p4) {
// check whether p1, p2, p3, p4 could form the square
vector<int> v1 = getVector(p1, p2), v2 = getVector(p4, p3);
if (v1 != v2) {
return false;
}
v1 = getVector(p1, p4), v2 = getVector(p2, p3);
if (v1 != v2) {
return false;
}
v2 = getVector(p1, p2);
int sl1 = squaredLength(v1), sl2 = squaredLength(v2);
return dotProduct(v1, v2) == 0 && sl1 == sl2 && sl1 > 0;
}
vector<int> getVector(vector<int> &p1, vector<int> &p2) {
return {p2[0] - p1[0], p2[1] - p1[1]};
}
};