Problem Description
Given the positions of trees in a garden, determine the minimum rope needed to enclose all the trees. In other words, return all the tree coordinates that lie on the perimeter of the fence. Note that if trees lie along an edge (i.e. are collinear), they should all be included.
Key Insights
- The problem is essentially about computing the convex hull but requires including all collinear points on the boundary.
- A common approach is to use the Gift Wrapping (Jarvis March) algorithm which “wraps” the set of points.
- While selecting the next hull point, handle collinear cases by checking points that lie on the line between the current point and the candidate.
- An orientation function (using cross product) is the key to comparing turns and detecting collinearity.
Space and Time Complexity
Time Complexity: O(nh) in worst-case (where n is the number of trees and h is the number of hull points) – often similar to O(n^2) in worst-case scenarios. Space Complexity: O(n) for storing the result and helper data structures.
Solution
We can solve this problem with the Jarvis March algorithm. The algorithm works as follows:
- Identify the leftmost point as the starting point.
- Set the current point and iterate to find the next candidate such that for every other point, the triplet (current, candidate, other) forms a clockwise turn. If points are collinear (zero cross-product), pick the furthest one as the candidate.
- After determining a candidate, iterate through all points again to collect every tree that is collinear with the edge from the current point to the candidate. This ensures that all collinear boundary points are included.
- Repeat until the starting point is reached.
The orientation is determined via the cross product. A positive result indicates a counterclockwise (left) turn, a negative indicates a clockwise (right) turn, and zero indicates collinearity.
This approach uses simple loops and geometric calculations to methodically “wrap” the set of points, ensuring every point on the boundary is included.