537. Erect the Fence (Convex Hull Problem)

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 theminimum lengthof 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.

Thoughts:

  1. Find the next convex "base" point, expand the co-linear points with it by using the Cross Product. (reason)

  2. Repeat doing this until the graph traverses back to the original point.

  3. This is essentially Jarvis'algorithm (or wrapping) with co-linear checks. (Other ways to solve convex Hull include Graham Scan, Simple Divide and Conquer Algorithm, and )

  4. Time Complexity of three Algorithm:

    Jarvis

    Graham Scan

    Andrew's Monotone Chain

    Divide and Conquer

    O(n^2)

    O(nlogn)

    O(nlogn)

    O(n^3)

Note: Cross Product = 0 <=> 1. there is a zero vector (current point reaches the base point) 2. two vectors are parallel (or anti-parallel, the angle between is either 0 or 180 degree)

Code Monotone Chain:

Other two comparable solutions: 1, 2.

Code Monotone Chain (Python):

Code Graham Scan:

Code Javis's Algorithm (Java)

Special Thanks to shawngao's solution and solution by GeeksforGeeks, lee215 and aeonaxx for providing Monotone Chain Solution and equivalent Python solution by awice, along with alternative solution 1 by zestypanda, and 2 by hwf.

Last updated

Was this helpful?