Problem Description
You are given a 3 x 3 grid that contains exactly 9 stones in total (with possibly multiple stones per cell). In one move you can take a single stone and move it to an adjacent cell (cells sharing a side). The goal is to have exactly one stone in every cell. Return the minimum number of moves required to achieve this.
Key Insights
- Each cell’s “imbalance” can be computed by subtracting 1 from its stone count.
- Cells with a surplus (value > 0) will act as donors while cells with a deficit (value < 0) will be recipients.
- Because the grid is small, we can list each donor stone (repeating coordinates according to the surplus) and each deficit cell (repeating coordinates according to the shortage) and then solve an assignment problem.
- The cost to move a stone from one cell to another is the Manhattan distance between the coordinates.
- We can solve the assignment problem using a dynamic programming solution with bitmasking to assign donor stones to deficit spots optimally.
Space and Time Complexity
Time Complexity: O(n * 2^n) where n is the total number of stones that need to be moved (at most 9 in the worst case), which is effectively constant. Space Complexity: O(2^n) for the DP array.
Solution
We first calculate the imbalance for every cell, where imbalance = grid[r][c] - 1. For cells with imbalance > 0, we create a list of donor locations repeated by the surplus amount. For cells with imbalance < 0, we create a list of deficit locations repeated by the absolute value of the deficit.
Next, we precompute the Manhattan distance cost between every donor and every deficit. Then, we solve the assignment problem using a bitmask dynamic programming (DP) approach, where the DP state represents which deficit positions have already been paired with donor stones. At each step, we assign the next unassigned donor to any remaining deficit and update the cost accordingly. Finally, the minimum cost in the DP table yields the fewest moves needed.