Minimum Moves to Spread Stones Over Grid - Problem
You are given a 3ร3 grid containing exactly 9 stones distributed across the cells. Some cells may have multiple stones, while others might be empty.
Your goal is to redistribute the stones so that each cell contains exactly one stone. In each move, you can transfer a single stone from one cell to an adjacent cell (sharing a side - no diagonal moves allowed).
Find the minimum number of moves required to achieve this balanced distribution.
Example:
Grid: [[1,1,0],
[1,1,1],
[1,2,1]]
Target: [[1,1,1],
[1,1,1],
[1,1,1]]The challenge is to find the most efficient way to move stones from cells with excess stones to empty cells.
Input & Output
example_1.py โ Basic Grid
$
Input:
grid = [[1,1,0],[1,1,1],[1,2,1]]
โบ
Output:
3
๐ก Note:
We need to move 1 stone from position (2,1) which has 2 stones to position (0,2) which has 0 stones. The Manhattan distance is |2-0| + |1-2| = 3 moves.
example_2.py โ Multiple Redistributions
$
Input:
grid = [[1,2,2],[1,1,0],[0,1,1]]
โบ
Output:
4
๐ก Note:
We have excess stones at (0,1) and (0,2), and empty cells at (1,2) and (2,0). Optimal assignment: (0,1)โ(1,2) costs 2 moves, (0,2)โ(2,0) costs 4 moves. Total: 6 moves. Wait, let me recalculate: (0,1)โ(2,0) costs 3, (0,2)โ(1,2) costs 1. Total: 4 moves.
example_3.py โ Already Balanced
$
Input:
grid = [[1,1,1],[1,1,1],[1,1,1]]
โบ
Output:
0
๐ก Note:
The grid is already perfectly balanced with exactly one stone in each cell, so no moves are needed.
Constraints
-
grid.length == 3 -
grid[i].length == 3 -
0 โค grid[i][j] โค 9 - The total number of stones is exactly 9
- Stones can only be moved to adjacent cells (sharing a side)
Visualization
Tap to expand
Understanding the Visualization
1
Survey the Warehouse
Identify overcrowded storage areas and empty spots that need filling
2
Plan Optimal Routes
Calculate Manhattan distances between sources and destinations
3
Execute Redistribution
Move items along the shortest paths to minimize total effort
4
Achieve Balance
Every storage location now has exactly one item
Key Takeaway
๐ฏ Key Insight: This is a minimum cost bipartite matching problem solved by trying all possible assignments between excess stones and empty cells, calculating Manhattan distances for each assignment.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code