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 public class Solution { 2 public bool ValidSquare(int[] p1, int[] p2, int[] p3, int[] p4) { 3 var dict = new Dictionary<int, int>(); 4 var list = new List<int>(6); 5 6 list.Add(GetLengthSquare(p1, p2)); 7 list.Add(GetLengthSquare(p1, p3)); 8 list.Add(GetLengthSquare(p1, p4)); 9 list.Add(GetLengthSquare(p2, p3)); 10 list.Add(GetLengthSquare(p2, p4)); 11 list.Add(GetLengthSquare(p3, p4)); 12 13 foreach (var l in list) 14 { 15 if (!dict.ContainsKey(l)) 16 { 17 dict[l] = 1; 18 } 19 else 20 { 21 dict[l]++; 22 } 23 } 24 25 if (dict.Count != 2) return false; 26 27 foreach (var pair in dict) 28 { 29 if (pair.Value != 2 && pair.Value != 4) 30 { 31 return false; 32 } 33 } 34 35 return true; 36 } 37 38 private int GetLengthSquare(int[] p1, int[] p2) 39 { 40 return (int)Math.Pow((p2[0] - p1[0]), 2) + (int)Math.Pow((p2[1] - p1[1]), 2); 41 } 42 }