Leetcode #2850: Minimum Moves to Spread Stones Over Grid
In this guide, we solve Leetcode #2850 Minimum Moves to Spread Stones Over Grid in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Breadth-First Search, Array, Dynamic Programming, Matrix
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: grid = [[1,1,0],[1,1,1],[1,2,1]]
Output: 3
Explanation: One possible sequence of moves to place one stone in each cell is:
1- Move one stone from cell (2,1) to cell (2,2).
2- Move one stone from cell (2,2) to cell (1,2).
3- Move one stone from cell (1,2) to cell (0,2).
In total, it takes 3 moves to place one stone in each cell of the grid.
It can be shown that 3 is the minimum number of moves required to place one stone in each cell.
Python Solution
class Solution:
def minimumMoves(self, grid: List[List[int]]) -> int:
q = deque([tuple(tuple(row) for row in grid)])
vis = set(q)
ans = 0
dirs = (-1, 0, 1, 0, -1)
while 1:
for _ in range(len(q)):
cur = q.popleft()
if all(x for row in cur for x in row):
return ans
for i in range(3):
for j in range(3):
if cur[i][j] > 1:
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < 3 and 0 <= y < 3 and cur[x][y] < 2:
nxt = [list(row) for row in cur]
nxt[i][j] -= 1
nxt[x][y] += 1
nxt = tuple(tuple(row) for row in nxt)
if nxt not in vis:
vis.add(nxt)
q.append(nxt)
ans += 1
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.