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
Stone Distribution Problem: Balance the Grid110111111Input: Uneven DistributionMove Stones111111111Goal: Balanced GridMinimum Moves: 3
Understanding the Visualization
1
Input
3×3 grid with 9 stones unevenly distributed
2
Process
Move stones to achieve exactly 1 stone per cell
3
Output
Minimum number of moves required
Key Takeaway
🎯 Key Insight: Model as assignment problem - find optimal mapping of excess stones to empty cells using Manhattan distance
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