Ctrl K

Squirrel Hauling Nuts

Medium
A garden is a grid with rows rows and cols columns. A tree grows in cell tree, a squirrel sits in cell start, and nuts lie in the cells listed in nuts (each position is [row, column]). The squirrel has to bring every nut to the tree. It can carry at most one nut at a time, and each move takes it to a cell sharing a side with the current one. Return the smallest total number of moves needed to bring all the nuts to the tree.
Example 1
rows=4, cols=5, tree=[1, 1], start=[3, 4], nuts=[[0, 0], [2, 3]] → 9

First the squirrel walks to the nut at (2, 3) in 2 moves and carries it to the tree in 3. Then a round trip to (0, 0) takes 2 + 2. That is 9 in total.

Example 2
rows=1, cols=4, tree=[0, 0], start=[0, 3], nuts=[[0, 2]] → 3

One step to the nut and two steps carrying it to the tree.

Example 3
rows=3, cols=3, tree=[1, 1], start=[1, 1], nuts=[[0, 1], [2, 2]] → 6
Constraints
  • 1 ≤ rows, cols ≤ 100
  • 1 ≤ len(nuts) ≤ 10⁴
  • All positions are inside the grid: 0 ≤ row < rows, 0 ≤ column < cols
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTurn a Square Clockwise MediumPostfix Calculator MediumRoll an Array to the Right MediumPrimes Below a Bound MediumNth Number Built From Given Primes Medium
loading Python…
Input
rows=4, cols=5, tree=[1, 1], start=[3, 4], nuts=[[0, 0], [2, 3]]
Expected
9

Run checks the first 3 tests in your browser. Submit checks all 71 tests on the server, hidden ones included.