Problem
You are given two integers height
and width
representing a garden of size height x width
. You are also given:
- an array
tree
wheretree = [treer, treec]
is the position of the tree in the garden, - an array
squirrel
wheresquirrel = [squirrelr, squirrelc]
is the position of the squirrel in the garden, - and an array
nuts
wherenuts[i] = [nutir, nutic]
is the position of theith
nut in the garden.
The squirrel can only take at most one nut at one time and can move in four directions: up, down, left, and right, to the adjacent cell.
Return theminimal distance for the squirrel to collect all the nuts and put them under the tree one by one.
The distance is the number of moves.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= height, width <= 100
tree.length == 2
squirrel.length == 2
1 <= nuts.length <= 5000
nuts[i].length == 2
0 <= treer, squirrelr, nutir <= height
0 <= treec, squirrelc, nutic <= width
Solution
Method 1 – Greedy Calculation of First Nut
Intuition
The squirrel must collect all nuts and bring them to the tree, but it starts at a different position. For all but the first nut, the squirrel must go from the tree to the nut and back. For the first nut, the squirrel starts from its own position. To minimize the total distance, we choose the first nut so that the difference between the squirrel-to-nut and tree-to-nut distances is maximized.
Approach
- For each nut, calculate the distance from the tree and from the squirrel.
- The total cost is:
- For all nuts:
2 * distance(tree, nut)
(tree to nut and back) - For the first nut: replace one tree-to-nut with squirrel-to-nut
- So, total = sum of
2 * distance(tree, nut)
for all nuts, minus the maximumdistance(tree, nut) - distance(squirrel, nut)
- For all nuts:
- Return the minimal total distance.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, where n is the number of nuts. - 🧺 Space complexity:
O(1)
, only constant extra space is used.