here are some trees, where each tree is represented by (x,y) coordinate in a two-dimensional garden. Your job is to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed. Your task is to help find the coordinates of trees which are exactly located on the fence perimeter.
Example 1:
Input: [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]] Output: [[1,1],[2,0],[4,2],[3,3],[2,4]] Explanation:
Example 2:
Input: [[1,2],[2,2],[4,2]] Output: [[1,2],[2,2],[4,2]] Explanation: Even you only have trees in a line, you need to use rope to enclose them.
Note:
-----------------------------------------------------------------------
First Recall the diff between dot product (点乘,内积) and cross product(叉乘,外积):
So the solution could be illustrated with the following figure: If the degree of anti-clock rotating vector OA to vector AB is larger than 180, A isn't the convex point. Traverse all points with stack and merge the upper and down sides.
class Solution:
def cal_half(self, pts):
l, sta = len(pts), []
#v1:o->a v2:a->b
cross_product = lambda o, a, b: ((a[0] - o[0]) * (b[1] - a[1])) - ((a[1] - o[1]) * (b[0] - a[0]))
for i in range(l):
while (len(sta) > 1 and cross_product(sta[-2], sta[-1], pts[i]) < 0):
sta.pop()
sta.append( (pts[i][0],pts[i][1]))
return sta
def outerTrees(self, points):
pts = sorted(points, key=lambda p: (p[0], p[1]))
down, up = self.cal_half(pts), self.cal_half(pts[::-1])
# return down+up bug1: dup for triangle
return [list(item) for item in set(down+up)]
s = Solution()
print(s.outerTrees([[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]))