1. 程式人生 > >Leetcode 593.有效正方形

Leetcode 593.有效正方形

font alt family [1] ble 一個點 png swa bubuko

有效正方形

給定二維空間中四點的坐標,返回四點是否可以構造一個正方形。

一個點的坐標(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 }

Leetcode 593.有效正方形