LeetCode 587. Erect the Fence 凸包 向量叉积

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:

  1. All trees should be enclosed together. You cannot cut the rope to enclose trees that will separate them in more than one group.
  2. All input integers will range from 0 to 100.
  3. The garden has at least one tree.
  4. All coordinates are distinct.
  5. Input points have NO order. No order required for output.
  6. input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

-----------------------------------------------------------------------

First Recall the diff between dot product (点乘,内积) and cross product(叉乘,外积):

  1. Dot product: Assume two vector A=[x1,y1,z1] B=[x2,y2,z2]. A*B = x1*x2+y1*y2+z1*z2. The result of dot product is a real number. A*B = |A|*|B|*cosθ. Dot product describe the similarity.
  2. Cross product: Assume two vector A=[x1,y1,z1] B=[x2,y2,z2]. The result of cross product is a vector. |A*B| = |A|*|B|*sinθ*n, and n is a unit vector perpendicular to the plane containing A and B in the direction given by the right-hand rule. 

LeetCode 587. Erect the Fence 凸包 向量叉积_第1张图片

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.

 

LeetCode 587. Erect the Fence 凸包 向量叉积_第2张图片

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]]))

 

你可能感兴趣的:(算法,leetcode)