Minimum Moves to Spread Stones Over Grid - Problem

You are given a 0-indexed 2D integer matrix grid of size 3 × 3, representing the number of stones in each cell. The grid contains exactly 9 stones, and there can be multiple stones in a single cell.

In one move, you can move a single stone from its current cell to any other cell if the two cells share a side (adjacent horizontally or vertically).

Return the minimum number of moves required to place one stone in each cell.

Input & Output

Example 1 — Uneven Distribution
$ Input: grid = [[1,1,0],[1,1,1],[1,1,1]]
Output: 3
💡 Note: One stone needs to move from (1,1) to (0,2) costing 3 moves. Two stones can move from nearby positions to reach the empty cell optimally.
Example 2 — Already Balanced
$ Input: grid = [[1,1,1],[1,1,1],[1,1,1]]
Output: 0
💡 Note: Grid already has exactly one stone in each cell, so no moves are needed.
Example 3 — Corner Case
$ Input: grid = [[3,2,2],[0,1,1],[0,1,1]]
Output: 4
💡 Note: Need to move 2 stones from (0,0) and 1 stone each from (0,1) and (0,2) to empty corners. Minimum total Manhattan distance is 4.

Constraints

  • grid.length == 3
  • grid[i].length == 3
  • 0 ≤ grid[i][j] ≤ 9
  • Sum of grid[i][j] == 9

Visualization

Tap to expand
Minimum Moves to Spread Stones Over Grid INPUT 1 1 0 1 1 1 1 1 1 3x3 grid with 9 stones total Cell [0,2] is empty (needs stone) grid = [[1,1,0], [1,1,1], [1,1,1]] ALGORITHM STEPS 1 Find Empty Cells Identify cells with 0 stones 2 Find Excess Stones Cells with more than 1 stone 3 Backtrack All Paths Try moving stones to empties 4 Prune and Minimize Track minimum moves found 1 1 0 Move stone from [0,1] to [0,2] Manhattan distance = steps Recursively try all permutations FINAL RESULT 1 1 1 1 1 1 1 1 1 Each cell has exactly 1 stone Output: 3 Minimum moves = 3 (OK) Key Insight: Backtracking explores all ways to match excess stones with empty cells. For each empty cell, try moving a stone from every source (cells with stones greater than 1). The cost is Manhattan distance. Pruning stops branches that exceed current minimum. Time: O(n!) where n = empty cells. TutorialsPoint - Minimum Moves to Spread Stones Over Grid | Backtracking with Pruning
Asked in
Google 15 Amazon 12 Microsoft 8
17.9K Views
Medium Frequency
~25 min Avg. Time
687 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen