Erect The Fence Problem
Description
LeetCode Problem 587.
You are given an array trees where trees[i] = [x_i, y_i] represents the location of a tree in the garden.
You are asked 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.
Return the coordinates of trees that are exactly located on the fence perimeter.
Example 1:
Input: points = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]
Output: [[1,1],[2,0],[3,3],[2,4],[4,2]]
Example 2:
Input: points = [[1,2],[2,2],[4,2]]
Output: [[4,2],[2,2],[1,2]]
Constraints:
- 1 <= points.length <= 3000
- points[i].length == 2
- 0 <= x_i, y_i <= 100
- All the given points are unique.
Solution
Approach: Monotone Chain Convex Hull
The shortest rope around all trees is the convex hull of the points, and the answer is every tree on its boundary, including trees that lie on a straight edge between two corners.
The tool is the cross product cross(o, a, b) = (a.x - o.x)(b.y - o.y) - (a.y - o.y)(b.x - o.x). It is positive when o -> a -> b turns left, negative when it turns right, and 0 when the three points are on one line.
- Sort the points by
x, then byy. - Lower half: go through the points left to right with a stack. Before pushing a point, pop the top of the stack while the last two stack points and the new point make a right turn (
cross < 0). The stack then holds the bottom boundary. - Upper half: do the same going right to left. Walking in the opposite direction, the same rule keeps the top boundary.
- Mark every point that ended up in either stack, and return the marked points.
The detail that matters is popping only on a strict right turn. Popping on cross == 0 too would build the usual hull with corners only, and drop trees in the middle of an edge, such as [2,2] in Example 2.
Each half's two end points (the leftmost and rightmost) appear in both stacks, and when all points are on one line every point does. Marking points instead of appending the two stacks makes sure each tree is returned once.
Complexity: O(n log n) time for the sort (each point is pushed and popped at most once per half), and O(n) space, where n is the number of trees.
class Solution:
def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:
def cross(o: List[int], a: List[int], b: List[int]) -> int:
"""> 0 for a left (counter-clockwise) turn o -> a -> b, < 0 for a right turn, 0 if collinear."""
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
points = sorted(trees) # by x, then by y
n = len(points)
on_fence = [False] * n
def build_half(order: List[int]) -> None:
hull = [] # indices into points
for i in order:
# Drop the last point while it makes a right turn; collinear points stay on the fence.
while len(hull) >= 2 and cross(points[hull[-2]], points[hull[-1]], points[i]) < 0:
hull.pop()
hull.append(i)
for i in hull:
on_fence[i] = True
build_half(list(range(n))) # lower half, left to right
build_half(list(range(n - 1, -1, -1))) # upper half, right to left
return [points[i] for i in range(n) if on_fence[i]]