Squirrel Simulation - Problem
You are given two integers height and width representing a garden of size height x width. You are also given:
- An array
treewheretree = [treer, treec]is the position of the tree in the garden - An array
squirrelwheresquirrel = [squirrelr, squirrelc]is the position of the squirrel in the garden - An array
nutswherenuts[i] = [nutir, nutic]is the position of the ith 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 the minimal 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.
Input & Output
Example 1 — Basic Garden
$
Input:
height = 5, width = 7, tree = [2,2], squirrel = [4,4], nuts = [[3,0], [2,5]]
›
Output:
12
💡 Note:
Squirrel collects nut at [3,0] first (distance 5), brings to tree (distance 3), then goes to [2,5] (distance 3), and brings back (distance 3). Total: 5+3+3+3 = 14. But optimal is 12 by choosing [2,5] first.
Example 2 — Single Nut
$
Input:
height = 1, width = 3, tree = [0,1], squirrel = [0,0], nuts = [[0,2]]
›
Output:
3
💡 Note:
Squirrel at [0,0] goes to nut at [0,2] (distance 2), then to tree at [0,1] (distance 1). Total: 2+1 = 3.
Example 3 — Multiple Nuts Close Together
$
Input:
height = 3, width = 3, tree = [1,1], squirrel = [0,0], nuts = [[0,1], [1,0], [2,1]]
›
Output:
6
💡 Note:
Base distance is 2×(1+1+1) = 6. Best savings comes from choosing optimal first nut, but all have same savings of 0. Total remains 6.
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
Visualization
Tap to expand
Understanding the Visualization
1
Input Setup
Garden with squirrel, tree, and multiple nuts at different positions
2
Collection Process
Squirrel moves to nut, picks it up, brings to tree, repeats for all nuts
3
Optimization
Find order that minimizes total Manhattan distance traveled
Key Takeaway
🎯 Key Insight: Only the first nut collection matters for optimization since squirrel ends up at tree afterward
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code