Leetcode 593.有效正方形

有效正方形

给定二维空间中四点的坐标,返回四点是否可以构造一个正方形。

一个点的坐标(x,y)由一个有两个整数的整数数组表示。

示例:

输入: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]

输出: True

   

注意:

  1. 所有输入整数都在 [-10000,10000] 范围内。
  2. 一个有效的正方形有四个等长的正长和四个等角(90度角)。
  3. 输入点没有顺序。

 

 1 public class Solution {
 2     public double dist(int[] p1, int[] p2) {
 3         return (p2[1] - p1[1]) * (p2[1] - p1[1]) + (p2[0] - p1[0]) * (p2[0] - p1[0]);
 4     }
 5     public boolean check(int[] p1, int[] p2, int[] p3, int[] p4) {
 6         return dist(p1,p2) > 0 && dist(p1, p2) == dist(p2, p3) && dist(p2, p3) == dist(p3, p4) && dist(p3, p4) == dist(p4, p1) && dist(p1, p3) == dist(p2, p4);
 7     }
 8     public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
 9         int[][] p = {p1,p2,p3,p4};
10         return checkAllPermutations(p, 0);
11     }
12     boolean checkAllPermutations(int[][] p, int l) {
13         if (l == 4) {
14             return check(p[0], p[1], p[2], p[3]);
15         } else {
16             boolean res = false;
17             for (int i = l; i < 4; i++) {
18                 swap(p, l, i);
19                 res |= checkAllPermutations(p, l + 1);
20                 swap(p, l, i);
21             }
22             return res;
23         }
24     }
25     public void swap(int[][] p, int x, int y) {
26         int[] temp = p[x];
27         p[x] = p[y];
28         p[y] = temp;
29     }
30 }

 

 

原文地址:https://www.cnblogs.com/kexinxin/p/10381401.html