Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
Return the minimum number of moves required to place one stone in each cell.
Example 1:
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.
Example 2:
Input: grid = [[1,3,0],[1,0,0],[1,0,3]] Output: 4 Explanation: One possible sequence of moves to place one stone in each cell is: 1- Move one stone from cell (0,1) to cell (0,2). 2- Move one stone from cell (0,1) to cell (1,1). 3- Move one stone from cell (2,2) to cell (1,2). 4- Move one stone from cell (2,2) to cell (2,1). In total, it takes 4 moves to place one stone in each cell of the grid. It can be shown that 4 is the minimum number of moves required to place one stone in each cell.
Constraints:
grid.length == grid[i].length == 30 <= grid[i][j] <= 9grid is equal to 9.Problem summary: 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. Return the minimum number of moves required to place one stone in each cell.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Backtracking · Bit Manipulation
[[1,1,0],[1,1,1],[1,2,1]]
[[1,3,0],[1,0,0],[1,0,3]]
minimum-number-of-operations-to-move-all-balls-to-each-box)minimum-number-of-operations-to-make-x-and-y-equal)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2850: Minimum Moves to Spread Stones Over Grid
class Solution {
public int minimumMoves(int[][] grid) {
Deque<String> q = new ArrayDeque<>();
q.add(f(grid));
Set<String> vis = new HashSet<>();
vis.add(f(grid));
int[] dirs = {-1, 0, 1, 0, -1};
for (int ans = 0;; ++ans) {
for (int k = q.size(); k > 0; --k) {
String p = q.poll();
if ("111111111".equals(p)) {
return ans;
}
int[][] cur = g(p);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (cur[i][j] > 1) {
for (int d = 0; d < 4; ++d) {
int x = i + dirs[d];
int y = j + dirs[d + 1];
if (x >= 0 && x < 3 && y >= 0 && y < 3 && cur[x][y] < 2) {
int[][] nxt = new int[3][3];
for (int r = 0; r < 3; ++r) {
for (int c = 0; c < 3; ++c) {
nxt[r][c] = cur[r][c];
}
}
nxt[i][j]--;
nxt[x][y]++;
String s = f(nxt);
if (!vis.contains(s)) {
vis.add(s);
q.add(s);
}
}
}
}
}
}
}
}
}
private String f(int[][] grid) {
StringBuilder sb = new StringBuilder();
for (int[] row : grid) {
for (int x : row) {
sb.append(x);
}
}
return sb.toString();
}
private int[][] g(String s) {
int[][] grid = new int[3][3];
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
grid[i][j] = s.charAt(i * 3 + j) - '0';
}
}
return grid;
}
}
// Accepted solution for LeetCode #2850: Minimum Moves to Spread Stones Over Grid
type Queue []string
func (q *Queue) Push(s string) {
*q = append(*q, s)
}
func (q *Queue) Pop() string {
s := (*q)[0]
*q = (*q)[1:]
return s
}
func (q *Queue) Empty() bool {
return len(*q) == 0
}
func minimumMoves(grid [][]int) int {
q := Queue{f(grid)}
vis := map[string]bool{f(grid): true}
dirs := []int{-1, 0, 1, 0, -1}
for ans := 0; ; ans++ {
sz := len(q)
for ; sz > 0; sz-- {
p := q.Pop()
if p == "111111111" {
return ans
}
cur := g(p)
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if cur[i][j] > 1 {
for d := 0; d < 4; d++ {
x, y := i+dirs[d], j+dirs[d+1]
if x >= 0 && x < 3 && y >= 0 && y < 3 && cur[x][y] < 2 {
nxt := make([][]int, 3)
for r := range nxt {
nxt[r] = append([]int(nil), cur[r]...)
}
nxt[i][j]--
nxt[x][y]++
s := f(nxt)
if !vis[s] {
vis[s] = true
q.Push(s)
}
}
}
}
}
}
}
}
}
func f(grid [][]int) string {
var sb strings.Builder
for _, row := range grid {
for _, x := range row {
sb.WriteByte(byte(x) + '0')
}
}
return sb.String()
}
func g(s string) [][]int {
grid := make([][]int, 3)
for i := range grid {
grid[i] = make([]int, 3)
for j := 0; j < 3; j++ {
grid[i][j] = int(s[i*3+j] - '0')
}
}
return grid
}
# Accepted solution for LeetCode #2850: Minimum Moves to Spread Stones Over Grid
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
// Accepted solution for LeetCode #2850: Minimum Moves to Spread Stones Over Grid
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #2850: Minimum Moves to Spread Stones Over Grid
// class Solution {
// public int minimumMoves(int[][] grid) {
// Deque<String> q = new ArrayDeque<>();
// q.add(f(grid));
// Set<String> vis = new HashSet<>();
// vis.add(f(grid));
// int[] dirs = {-1, 0, 1, 0, -1};
// for (int ans = 0;; ++ans) {
// for (int k = q.size(); k > 0; --k) {
// String p = q.poll();
// if ("111111111".equals(p)) {
// return ans;
// }
// int[][] cur = g(p);
// for (int i = 0; i < 3; ++i) {
// for (int j = 0; j < 3; ++j) {
// if (cur[i][j] > 1) {
// for (int d = 0; d < 4; ++d) {
// int x = i + dirs[d];
// int y = j + dirs[d + 1];
// if (x >= 0 && x < 3 && y >= 0 && y < 3 && cur[x][y] < 2) {
// int[][] nxt = new int[3][3];
// for (int r = 0; r < 3; ++r) {
// for (int c = 0; c < 3; ++c) {
// nxt[r][c] = cur[r][c];
// }
// }
// nxt[i][j]--;
// nxt[x][y]++;
// String s = f(nxt);
// if (!vis.contains(s)) {
// vis.add(s);
// q.add(s);
// }
// }
// }
// }
// }
// }
// }
// }
// }
//
// private String f(int[][] grid) {
// StringBuilder sb = new StringBuilder();
// for (int[] row : grid) {
// for (int x : row) {
// sb.append(x);
// }
// }
// return sb.toString();
// }
//
// private int[][] g(String s) {
// int[][] grid = new int[3][3];
// for (int i = 0; i < 3; ++i) {
// for (int j = 0; j < 3; ++j) {
// grid[i][j] = s.charAt(i * 3 + j) - '0';
// }
// }
// return grid;
// }
// }
// Accepted solution for LeetCode #2850: Minimum Moves to Spread Stones Over Grid
function minimumMoves(grid: number[][]): number {
const q: string[] = [f(grid)];
const vis: Set<string> = new Set([f(grid)]);
const dirs: number[] = [-1, 0, 1, 0, -1];
for (let ans = 0; ; ans++) {
let sz = q.length;
while (sz-- > 0) {
const p = q.shift()!;
if (p === '111111111') {
return ans;
}
const cur = g(p);
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (cur[i][j] > 1) {
for (let d = 0; d < 4; d++) {
const x = i + dirs[d],
y = j + dirs[d + 1];
if (x >= 0 && x < 3 && y >= 0 && y < 3 && cur[x][y] < 2) {
const nxt = cur.map(row => [...row]);
nxt[i][j]--;
nxt[x][y]++;
const s = f(nxt);
if (!vis.has(s)) {
vis.add(s);
q.push(s);
}
}
}
}
}
}
}
}
}
function f(grid: number[][]): string {
return grid.flat().join('');
}
function g(s: string): number[][] {
return Array.from({ length: 3 }, (_, i) =>
Array.from({ length: 3 }, (_, j) => Number(s[i * 3 + j])),
);
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Wrong move: Mutable state leaks between branches.
Usually fails on: Later branches inherit selections from earlier branches.
Fix: Always revert state changes immediately after recursive call.