Convex Polygon
Description:
Given a list of points that form a polygon when joined sequentially, find if this polygon is convex (Convex polygon definition).
Example
Given points = [[0, 0], [0, 1], [1, 1], [1, 0]],
return True.
Explanation:
https://lintcode-media.s3.amazonaws.com/problem/E3N5G.png
Given points = [[0, 0], [0, 10], [10, 10], [10, 0], [5, 5]],
return False.
Explanation
https://lintcode-media.s3.amazonaws.com/problem/E3f02.png
Notice
There are at least 3 and at most 10,000 points.
Coordinates are in the range -10,000 to 10,000.
You may assume the polygon formed by given points is always a simple polygon (Simple polygon definition). In other words, we ensure that exactly two edges intersect at each vertex, and that edges otherwise don’t intersect each other.
Code:
class Solution:
"""
@param point: a list of two-tuples
@return: a boolean, denote whether the polygon is convex
"""
def isConvex(self, point):
# write your code here
def crossProduct(a, b, c):
x0, y0 = a
x1, y1 = b
x2, y2 = c
return (x2-x0) * (y1-y0) - (x1-x0) * (y2-y0)
lenP = len(point)
pre = crossProduct(point[-1], point[0], point[1])
for i in range(lenP):
res = crossProduct(point[i%lenP], point[(i+1)%lenP], point[(i+2)%lenP])
if res*pre < 0:
print('res', res)
print('pre', pre)
return False
if res != 0:
pre = res
return True