LeetCode469 - Convex Polygon - Medium (Python)

Given a list of points that form a polygon when joined sequentially, find if this polygon is convex (Convex polygon definition).

[[0,0],[0,1],[1,1],[1,0]]

Answer: True
[[0, 0], [0,10], [10, 10], [10,0], [5,5]] 

Answer: False 

ideas: This question is asked a series of polygon to the point, it is determined that whether it is convex in. A better method is judgment to see if all points are sequentially arranged in accordance with the same, all such points are sequentially clockwise, counterclockwise or aligned with a line.
Here's a method to determine the direction, someone used the po on LeetCode Robert Sedgewick's Algorithm Course in content.
Determining whether or not the three points are arranged in one direction, we can first calculate (b [0] -a [0 ]) * (c [1] -a [1]) - (b [1] -a [1]) * (c [0] -a [ 0]). If this value is greater than zero, it means that is counterclockwise, if less than zero, then clockwise.
If equal to 0, it means that is arranged in the same line. So we can turn on three points each point above formula is calculated, as well as preservation and the direction of three points this time before three o'clock, and if not present, then we can simply
return False. Note that this calculation also starts from i = 0 when i = 0, when the point determined exactly points [-2], points [-1 ], points [0].
Difficult problem is how this determination Convex.

class Solution:
    def isConvex(self, points: List[List[int]]) -> bool:
        def direction(a,b,c):
            return (b[0]-a[0])*(c[1]-a[1]) - (b[1]-a[1])*(c[0]-a[0])
        d = None
        for i in range(len(points)):
            a = direction(points[i-2],points[i-1],points[i])
            if a == 0: continue
            if d == None: d = a
            else:
                if a*d < 0: return False
        
        return True

 

Guess you like

Origin www.cnblogs.com/sky37/p/12244380.html