[LeetCode] Valid Square

593. Valid Square

Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square.

The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order.

A valid square has four equal sides with positive length and four equal angles (90-degree angles).

1
2
3
4
5
6
7
8
9
10
class Solution {
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]);
}
public:
bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
unordered_set<int> s{dis(p1,p2), dis(p1,p3), dis(p1,p4), dis(p2,p3), dis(p2,p4), dis(p3,p4)};
return !s.count(0) and s.size() == 2;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/12/PS/LeetCode/valid-square/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.