Spread Nine Stones Across a Three-by-Three Grid with Minimum Moves
Company: American
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Online Assessment
Overview: Find the fewest orthogonal stone moves required to leave exactly one stone in every cell of a three-by-three grid.
Read the full American Software Engineer interview experience this question came from
Constraints
- `grid` has exactly three rows, each containing three integers.
- `0 <= grid[r][c] <= 9`.
- The sum of all nine entries is exactly 9.
- A move is one step up, down, left, or right within the grid; diagonal moves are not allowed.
- A cell may temporarily contain more than one stone, and every stone is identical with each one-step move costing one.
- Do not mutate the input grid; the caller may reuse it after the call.
- The returned count fits in a 32-bit signed integer (it never exceeds 36), so no 64-bit type is required.
Examples
Input: ([[1, 1, 1], [1, 1, 1], [1, 1, 1]],)
Expected Output: 0
Explanation: Minimum valid case: every cell already holds exactly one stone, so no cell is in surplus or deficit and zero moves are needed.
Input: ([[1, 1, 0], [1, 1, 1], [1, 2, 1]],)
Expected Output: 3
Explanation: Source example 1: the only extra stone sits at (2,1) and the only empty cell is (0,2); |2-0| + |1-2| = 3 moves.
Hints
- Every cell holding more than one stone has extras it must send away, and every empty cell must receive exactly one stone. Start by counting how many stones are in surplus and how many cells are empty, and convince yourself those two counts are always equal.
- Because steps are orthogonal and a cell may hold several stones along the way, one stone travelling from (r1,c1) to (r2,c2) costs exactly |r1 - r2| + |c1 - c2| moves, independent of every other stone.
- The number of surplus stones is small (at most eight). Ask whether sending a stone to the empty cell that happens to be closest to it can force a much more expensive trip for some other stone.