Share my code using inner product = 0 when right angle


  • 0
    T

    Basic Idea : if ABCD is a square, then A, B, C ,D are right angles, AC and BD are perpendicular.

    from operator import itemgetter
    class Solution(object):
        def isRightangle(self, v1, v2)
            return True if v1[0]*v2[0]+v1[1]*v2[1] == 0 else False 
    
        def ordered(self, pts):
            # ordered by x-coordinate and then by y-coordinate
            pts = sorted(pts, key=itemgetter(0,1))
            return pts
    
        def validSquare(self, p1, p2, p3, p4):
            """
            :type p1: List[int]
            :type p2: List[int]
            :type p3: List[int]
            :type p4: List[int]
            :rtype: bool
            """
            pts = [p1,p2,p3,p4]
            pts = self.ordered(pts)
            if pts[0] == pts[1] or pts[1] == pts[2]  or pts[2] == pts[3]:
                return False
            v01 = [pts[0][0]-pts[1][0],pts[0][1]-pts[1][1]]
            v02 = [pts[0][0]-pts[2][0],pts[0][1]-pts[2][1]]
            v03 = [pts[0][0]-pts[3][0],pts[0][1]-pts[3][1]]
            v12 = [pts[1][0]-pts[2][0],pts[1][1]-pts[2][1]]
            v13 = [pts[1][0]-pts[3][0],pts[1][1]-pts[3][1]]
            v23 = [pts[2][0]-pts[3][0],pts[2][1]-pts[3][1]]
            # Check all angles are right angle
            return self.isRightangle(v01,v02) and self.isRightangle(v01,v13) and self.isRightangle(v13,v23) and self.isRightangle(v23,v02) and self.isRightangle(v03,v12)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.