Tuesday, August 4, 2020

LeetCode [593] Valid Square

593. Valid Square
Medium

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:

  1. All the input integers are in the range [-10000, 10000].
  2. A valid square has four equal sides with positive length and four equal angles (90-degree angles).
  3. Input points have no order.

 

class Solution {
    public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
        int[][] list = new int[4][];
        list[0] = p1;
        list[1] = p2;
        list[2] = p3;
        list[3] = p4;

        //line i-j and line k-t are diagonals
        //they should cross eachother int the middle
        //they should have equal length
        //the neigher edge length should be equal
        for(int i=0; i<4; ++i){
            for(int j=0; j<4; ++j){
                if(j==i) continue;
                for(int k=0; k<4; ++k){
                    if(k==i || k==j) continue;
                    for(int t=0; t<4; ++t){
                        if(t==i || t==j || t==k) continue;
                        if(list[i][0]+list[j][0] != list[k][0]+list[t][0]) continue; 
                        if(list[i][1]+list[j][1] != list[k][1]+list[t][1]) continue;
                        if(Math.pow(list[i][0]-list[k][0], 2) + Math.pow(list[i][1]-list[k][1], 2) != Math.pow(list[k][0]-list[j][0], 2) + Math.pow(list[k][1]-list[j][1], 2) ) continue;
                        if(Math.pow(list[i][0]-list[j][0], 2) + Math.pow(list[i][1]-list[j][1], 2) != Math.pow(list[k][0]-list[t][0], 2) + Math.pow(list[k][1]-list[t][1], 2) ) continue;
                        return !(p1[0]==p2[0]&&p1[1]==p2[1]);
                    }
                }
            }
        }
        return false;
    }
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
    public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
        return helper(p1, p2, p3, p4)||helper(p1, p3, p2, p4)||helper(p1, p4, p2, p3);
    }

    double distance(int[] p, int[] q){
        return Math.pow(p[0]-q[0], 2) + Math.pow(p[1]-q[1], 2);
    }

    boolean helper(int[] p1, int[] p3, int[] p2, int[] p4) {
        if(p1[0]==p2[0] && p1[1]==p2[1]) return false;
        if(p1[0]+p3[0] != p2[0] + p4[0]) return false;
        if(p1[1]+p3[1] != p2[1] + p4[1]) return false;
        if(distance(p1, p3)!=distance(p2, p4)) return false;
        if(distance(p1, p2)!=distance(p1, p4)) return false;
        return true;
    }
}

No comments:

Post a Comment