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
๐Ÿ“ฆ Warehouse Stone RedistributionInitial State:๐Ÿ“ฆ๐Ÿ“ฆโŒ๐Ÿ“ฆ๐Ÿ“ฆ๐Ÿ“ฆ๐Ÿ“ฆ๐Ÿ“ฆ๐Ÿ“ฆ๐Ÿ“ฆFinal State:๐Ÿ“ฆ๐Ÿ“ฆ๐Ÿ“ฆ๐Ÿ“ฆ๐Ÿ“ฆ๐Ÿ“ฆ๐Ÿ“ฆ๐Ÿ“ฆ๐Ÿ“ฆ3 moves๐Ÿ“ Manhattan Distance: |2-0| + |1-2| = 3๐ŸŽฏ Total moves needed: 3โœ… Optimal solution found!
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.
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 4
28.6K Views
Medium Frequency
~15 min Avg. Time
1.2K 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