Problem
You are given a 2D integer array trees
where trees[i] = [xi, yi]
represents the location of the ith
tree in the garden.
You are asked to fence the entire garden using the minimum length of rope possible. The garden is well-fenced only if all the trees are enclosed and the rope used forms a perfect circle. A tree is considered enclosed if it is inside or on the border of the circle.
More formally, you must form a circle using the rope with a center (x, y)
and radius r
where all trees lie inside or on the circle and r
is
minimum.
Return the center and radius of the circle as a length 3 array[x, y, r]
. Answers within 10-5
of the actual answer will be accepted.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= trees.length <= 3000
trees[i].length == 2
0 <= xi, yi <= 3000
Solution
Method 1 – Welzl’s Algorithm (Smallest Enclosing Circle)
Intuition
The minimum rope length that forms a perfect circle enclosing all trees is the smallest enclosing circle (also called the minimum enclosing circle). Welzl’s algorithm is a randomized, recursive algorithm that efficiently finds this circle in expected linear time.
Approach
- Shuffle the points randomly to ensure average-case performance.
- Use Welzl’s recursive algorithm:
- If no points or 3 boundary points, compute the circle directly.
- Otherwise, remove a point and recursively find the circle for the rest.
- If the removed point is inside the circle, return the circle.
- If not, add the point to the boundary and recurse.
- For 0, 1, 2, or 3 boundary points, compute the circle directly:
- 0: return invalid.
- 1: center is the point, radius 0.
- 2: center is midpoint, radius is half the distance.
- 3: compute the unique circle passing through all three points.
- Return the center and radius.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
expected, due to randomization and recursion. - 🧺 Space complexity:
O(n)
for recursion and storage.