Squirrel Simulation Problem
Description
LeetCode Problem 573.
You are given two integers height and width representing a garden of size height x width. You are also given:
- an array
treewheretree = [tree_r, tree_c]is the position of the tree in the garden, - an array
squirrelwheresquirrel = [squirrel_r, squirrel_c]is the position of the squirrel in the garden, - and an array
nutswherenuts[i] = [nut_ir, nut_ic]is the position of thei^thnut 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.
Example 1:

Input: height = 5, width = 7, tree = [2,2], squirrel = [4,4], nuts = [[3,0], [2,5]]
Output: 12
Explanation: The squirrel should go to the nut at [2, 5] first to achieve a minimal distance.
Example 2:

Input: height = 1, width = 3, tree = [0,1], squirrel = [0,0], nuts = [[0,2]]
Output: 3
Constraints:
1 <= height, width <= 100tree.length == 2squirrel.length == 21 <= nuts.length <= 5000nuts[i].length == 20 <= tree_r, squirrel_r, nut_ir <= height0 <= tree_c, squirrel_c, nut_ic <= width
Solution
Approach: Pick the Best First Nut
There are no obstacles, so the distance between two cells is just the Manhattan distance |r1 - r2| + |c1 - c2|.
Look at the squirrel's route. Once a nut has been dropped under the tree, the squirrel is back at the tree, so every nut after the first costs a round trip: tree to nut and back, 2 * d(nut, tree). Only the very first nut is different: the squirrel walks to it from its starting point, d(squirrel, nut) + d(nut, tree).
So if every nut were a round trip, the total would be total = sum of 2 * d(nut, tree). Choosing nut x as the first one changes this by d(squirrel, x) - d(x, tree). The answer is total plus the smallest such change over all nuts. The order of the remaining nuts does not matter at all.
The tricky part is that the first nut is not simply the one closest to the squirrel. We want the nut where going there from the squirrel is cheapest compared with going there from the tree. In example 1, the nut at [2,5] is chosen: it is 3 moves from the squirrel and 3 from the tree, so it costs nothing extra, while [3,0] would cost 5 instead of 3.
Complexity: O(n) time for n nuts and O(1) extra space.
class Solution:
def minDistance(self, height: int, width: int, tree: List[int], squirrel: List[int], nuts: List[List[int]]) -> int:
def dist(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
# Every nut costs a round trip from the tree...
total = sum(2 * dist(nut, tree) for nut in nuts)
# ...except the first one, where the squirrel starts from its own position instead of the tree.
return total + min(dist(squirrel, nut) - dist(nut, tree) for nut in nuts)