Equalizing Nine Stones Across a 3x3 Grid
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
A 3 x 3 board grid holds 9 stones distributed across its nine squares, where grid[r][c] gives the initial stone count at row r and column c (0 <= r, c < 3). Individual squares may start empty (0) or hold stacks of multiple stones.
During each step, you may pick up one stone from any non-empty square and place it onto an edge-adjacent square (one row up/down or one column left/right). Intermediate stacks of arbitrary height are allowed.
Compute the smallest number of single-stone steps required so that all nine squares end up holding 1 stone apiece.
def minimum_moves(grid: list[list[int]]) -> int:
pass
Examples
Example 1
Input: grid = [
[0, 1, 1],
[1, 1, 1],
[1, 1, 2]
]
Output: 4
Only square (0, 0) is empty and only square (2, 2) holds an extra stone. Walking that extra stone two rows up and two columns left takes |2 - 0| + |2 - 0| = 4 steps.
Example 2
Input: grid = [
[4, 0, 0],
[1, 1, 0],
[1, 2, 0]
]
Output: 7
Four squares start empty: (0, 1), (0, 2), (1, 2), and (2, 2). Square (0, 0) has 3 extra stones and square (2, 1) has 1 extra stone:
- Send the extra stone at (2, 1) right to (2, 2) (1 step).
- Send the three extra stones at (0, 0) to (0, 1) (1 step), (0, 2) (2 steps), and (1, 2) (3 steps).
Total steps: 1 + 1 + 2 + 3 = 7.
Example 3
Input: grid = [
[0, 0, 2],
[1, 3, 0],
[0, 2, 1]
]
Output: 5
Empty squares sit at (0, 0), (0, 1), (1, 2), and (2, 0), while extra stones sit at (0, 2) (+1), (1, 1) (+2), and (2, 1) (+1). Sending (1, 1) -> (0, 0) (2 steps), (1, 1) -> (0, 1) (1 step), (0, 2) -> (1, 2) (1 step), and (2, 1) -> (2, 0) (1 step) achieves the optimal total of 5 steps.
Constraints
len(grid) == 3andlen(grid[r]) == 3for0 <= r < 30 <= grid[r][c] <= 9for all0 <= r, c < 3- The sum of all nine entries in
gridequals9
Step-by-step walkthrough
Understand the goal: surplus stones vs. empty cells
We receive a
3 x 3board holding9stones in total. Each move transfers a single stone up, down, left, or right into a neighboring cell, and we want the fewest moves so every cell finishes with1stone.Every cell plays one of three roles:
- Balanced (
grid[r][c] == 1): already holds the1stone it needs. - Empty (
grid[r][c] == 0): needs1stone delivered to it. - Surplus (
grid[r][c] > 1): retains1stone for itself and hasgrid[r][c] - 1extra stones that must depart.
Example 2 grid: Roles of each cell: col 0 col 1 col 2 [ 4, 0, 0 ] row 0 [ +3 extra, empty, empty ] [ 1, 1, 0 ] row 1 [ keep 1, keep 1, empty ] [ 1, 2, 0 ] row 2 [ keep 1, +1 extra, empty ]Because
9cells hold9stones altogether, the total count of extra stones across surplus cells always matches the number of empty cells.- Balanced (
Why moves equal Manhattan distances
Stones step one square at a time, yet two geometric facts let us skip individual hops and work directly with distances:
- No stone ever blocks another. Every cell can hold arbitrarily many passing stones at once, so a stone traveling from
(r1, c1)to(r2, c2)can always follow a shortest grid path of length|r1 - r2| + |c1 - c2|, known as the Manhattan distance. - Only surplus stones ever need to move. Suppose stone
Awalks into cellM, while stoneB(which started atM) walks onward to empty cellE. LeavingBparked inMand sendingAstraight toEobeys the triangle inequality (a direct path between two points is never longer than detouring via a third point), guaranteeingdist(A, E) <= dist(A, M) + dist(M, E):
Relay plan: A -----> M (B leaves M) -----> E cost = dist(A, M) + dist(M, E) Direct plan: A ----------------------------> E cost = dist(A, E) (never larger!) B stays home in MRepeating that exchange converts any valid step sequence into an equally short or shorter plan where every non-empty cell keeps one of its initial stones and each surplus stone walks straight to one empty cell. Our task reduces to matching each empty cell with one surplus stone to minimize total Manhattan distance.
- No stone ever blocks another. Every cell can hold arbitrarily many passing stones at once, so a stone traveling from
Why greedy fails and why backtracking is fast
A tempting shortcut is to assign each empty cell whichever surplus stone sits closest. That greedy rule breaks whenever two empty cells compete for the same nearby stone:
Grid: col 0 col 1 col 2 [ 0, 2, 0 ] row 0 Empty cells: (0, 0) and (0, 2) [ 1, 1, 1 ] row 1 Surplus (+1 each): (0, 1) and (2, 0) [ 2, 1, 1 ] row 2 Greedy (fill (0, 0) from nearest): (0, 1) -> (0, 0) costs 1, forcing (2, 0) -> (0, 2) at cost 4 => total = 5 (suboptimal!) Optimal pairing: (2, 0) -> (0, 0) costs 2, and (0, 1) -> (0, 2) costs 1 => total = 3Instead, we apply backtracking — systematically testing every available surplus cell for the current empty cell, recursing on the remaining empty cells, and restoring the count afterward so sibling branches start from a clean slate.
Why is exhaustive backtracking fast here? At most
8cells can be empty (8! = 40,320permutations at worst). Even better, extra stones stacked in the same cell are indistinguishable, so branching by source cell rather than individual stone visits at most90complete assignments (271recursive calls total) across all24,310valid3 x 3boards.Copy the grid and collect empty cells
Because backtracking temporarily decrements stone counts during the search, we copy
gridintocountsfirst so the caller's matrix is never mutated, then collect every(r, c)coordinate wherecounts[r][c] == 0intoempty_cells.def minimum_moves(grid: list[list[int]]) -> int: # Phase 1: Copy the 3x3 grid so backtracking never mutates the caller's input. # counts[r][c] stores how many stones currently sit in row r, column c. counts = [row[:] for row in grid] # empty_cells: list of (row, col) coordinates that start with 0 stones and need 1. empty_cells: List[Tuple[int, int]] = [] for r in range(3): for c in range(3): if counts[r][c] == 0: empty_cells.append((r, c))Backtrack over surplus sources for each empty cell
Next,
fill_empty_cells(empty_idx)computes the minimum moves required to satisfyempty_cells[empty_idx:]using the surplus stones still remaining incounts:- Base case: when
empty_idx == len(empty_cells), all empty cells are filled and0moves remain. - Recursive step: take
target_row, target_col = empty_cells[empty_idx]and try every(src_row, src_col)withcounts[src_row][src_col] > 1. Requiring strict> 1guarantees a cell never donates its final stone. - Decrement
counts[src_row][src_col], recurse onempty_idx + 1, and restorecounts[src_row][src_col]immediately upon return.
# Phase 2: Try every way to assign one surplus stone to each empty cell. def fill_empty_cells(empty_idx: int) -> int: # Base case: all empty cells have been paired with a surplus stone. if empty_idx == len(empty_cells): return 0 target_row, target_col = empty_cells[empty_idx] min_total_moves = float("inf") for src_row in range(3): for src_col in range(3): # Strictly > 1 because every occupied cell must keep 1 stone for itself; # only stones beyond the first are surplus that can move away. if counts[src_row][src_col] > 1: # Manhattan distance is exact because cells have unlimited capacity, # so stones never block one another on a shortest grid path. move_distance = abs(src_row - target_row) + abs(src_col - target_col) # Choose: spend one surplus stone from (src_row, src_col). counts[src_row][src_col] -= 1 remaining_moves = fill_empty_cells(empty_idx + 1) # Undo (backtrack): put the stone back so the next branch sees the same state. counts[src_row][src_col] += 1 candidate_moves = move_distance + remaining_moves if candidate_moves < min_total_moves: min_total_moves = candidate_moves return int(min_total_moves)- Base case: when
Trace Example 2 step by step
Let's trace
grid = [[4, 0, 0], [1, 1, 0], [1, 2, 0]]:empty_cells = [(0, 1), (0, 2), (1, 2), (2, 2)] Surplus sources at start: (0, 0) has count 4 (+3 extra), (2, 1) has count 2 (+1 extra) Winning branch: empty_idx = 0, target (0, 1) <- pick (0, 0): dist |0-0| + |0-1| = 1, counts[0][0] becomes 3 empty_idx = 1, target (0, 2) <- pick (0, 0): dist |0-0| + |0-2| = 2, counts[0][0] becomes 2 empty_idx = 2, target (1, 2) <- pick (0, 0): dist |0-1| + |0-2| = 3, counts[0][0] becomes 1 (no more extra!) empty_idx = 3, target (2, 2) <- pick (2, 1): dist |2-2| + |1-2| = 1, counts[2][1] becomes 1 empty_idx = 4 (base case) -> returns 0 Total = 1 + 2 + 3 + 1 = 7 Suboptimal branch (for comparison): If (2, 1) is spent early on (1, 2) (dist 2), then (2, 2) must pull from (0, 0) (dist 4), giving 1 + 2 + 2 + 4 = 9 > 7 (discarded).Every recursive branch restores
countscleanly on the way back up, andfill_empty_cells(0)returns7.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def minimum_moves(grid: list[list[int]]) -> int: # Phase 1: Copy the 3x3 grid so backtracking never mutates the caller's input. # counts[r][c] stores how many stones currently sit in row r, column c. counts = [row[:] for row in grid] # empty_cells: list of (row, col) coordinates that start with 0 stones and need 1. empty_cells: List[Tuple[int, int]] = [] for r in range(3): for c in range(3): if counts[r][c] == 0: empty_cells.append((r, c)) # Phase 2: Try every way to assign one surplus stone to each empty cell. def fill_empty_cells(empty_idx: int) -> int: # Base case: all empty cells have been paired with a surplus stone. if empty_idx == len(empty_cells): return 0 target_row, target_col = empty_cells[empty_idx] min_total_moves = float("inf") for src_row in range(3): for src_col in range(3): # Strictly > 1 because every occupied cell must keep 1 stone for itself; # only stones beyond the first are surplus that can move away. if counts[src_row][src_col] > 1: # Manhattan distance is exact because cells have unlimited capacity, # so stones never block one another on a shortest grid path. move_distance = abs(src_row - target_row) + abs(src_col - target_col) # Choose: spend one surplus stone from (src_row, src_col). counts[src_row][src_col] -= 1 remaining_moves = fill_empty_cells(empty_idx + 1) # Undo (backtrack): put the stone back so the next branch sees the same state. counts[src_row][src_col] += 1 candidate_moves = move_distance + remaining_moves if candidate_moves < min_total_moves: min_total_moves = candidate_moves return int(min_total_moves) return fill_empty_cells(0)✅ Submit now — all tests should pass.
Intuition & how it works
Picture 9 chairs arranged in a 3 x 3 room with 9 people sitting in them — some chairs have two, three, or four people squeezed together while other chairs sit empty. Nobody who already has their own chair needs to stand up; each extra person simply walks down the rows and columns to claim one empty chair, and we want the smallest combined walking distance across everyone who moves.
Simulating single-square nudges across full board states is needlessly intricate and obscures which extra stone ends up in which empty square. Conversely, a naive greedy rule — letting each empty square grab whichever extra stone sits closest — fails when an early square claims a nearby stone and forces a later square to pull a stone from across the board. Because squares can hold any number of passing stones at once, sending a stone from (r1, c1) to (r2, c2) always costs its Manhattan distance (|r1 - r2| + |c1 - c2|, the sum of vertical and horizontal grid steps), and we find the globally optimal assignment via backtracking (testing every eligible source square for each empty square one by one, and undoing each tentative choice before trying the next).
Let's walk through a compact example: grid = [[0, 2, 0], [1, 1, 1], [2, 1, 1]].
1. Scanning the board finds two empty squares, (0, 0) and (0, 2), and two squares with extra stones (count > 1), (0, 1) and (2, 0).
2. For the first empty square (0, 0), branch A assigns the extra stone at (0, 1) (distance 1), leaving (2, 0) for (0, 2) (distance 4), totaling 1 + 4 = 5 steps.
3. Backtracking restores (0, 1)'s count and explores branch B: (0, 0) takes the extra stone from (2, 0) (distance 2), leaving (0, 1) for (0, 2) (distance 1), totaling 2 + 1 = 3 steps.
4. Both branches complete, and the function returns min(5, 3) = 3.
Complexity
- Time:
O(1)because the board dimensions (3 x 3) and total stone count (9) are fixed constants. Withk <= 8empty squares, a raw permutation search visits at mostk! <= 40,320pairings, and branching by source square rather than individual stone merges identical stones in the same stack so the recursion makes at most271calls across all24,310valid boards (scanning9squares per call). - Space:
O(1)auxiliary memory, using only a3 x 3copy ofgrid, a list of at most8empty coordinates, and a recursion stack at most9frames deep.
Edge cases
- Already uniform (
all 1s):empty_cellsis empty, sofill_empty_cells(0)hits the base case right away and returns0. - All 9 stones stacked on a single square: only one square satisfies
count > 1, so every empty square draws from it; from a corner this costs1 + 2 + 1 + 2 + 3 + 2 + 3 + 4 = 18, and from the center(1, 1)it costs4 * 1 + 4 * 2 = 12. - Multiple extra stones stacked together (Example 2): checking
counts[r][c] > 1lets a square with4stones supply three distinct empty squares while retaining its final stone. - Tied distances: when two surplus squares sit equidistant from an empty square, backtracking explores both options so row/column scan order never biases the minimum.
- Input immutability: copying
gridintocountsguarantees the caller's list of lists stays unmodified.
Common mistakes
- Greedy nearest-neighbor pairing: matching each empty square to its closest remaining surplus stone fails on
[[0, 2, 0], [1, 1, 1], [2, 1, 1]](5instead of3). - Checking
counts[r][c] > 0instead ofcounts[r][c] > 1: a square holding1stone has zero surplus; letting it give away its stone leaves a new empty hole behind. - Forgetting
counts[src_row][src_col] += 1after recursion: without undoing the decrement on the way back up, later branches see missing stones and return wrong totals orinf. - Summing each empty square's distance to its closest surplus independently: two empty squares can pick the same lone extra stone, undercounting the true move cost.
Alternative approaches
- Permutations of an expanded surplus list: repeat each
(r, c)coordinategrid[r][c] - 1times and test permutations againstempty_cellsinO(k! * k)time (<= 8! * 8 = 322,560operations). Slightly more work when stones stack together, equally straightforward. - Bitmask dynamic programming: let
dp[mask]store the minimum steps to fill the subset of empty squares marked inmaskusing the firstpopcount(mask)expanded surplus stones inO(k * 2^k)time (<= 8 * 256 = 2,048operations). - Breadth-first search (BFS) over board states: treat the 9-tuple of stone counts as a graph vertex (
24,310reachable states) and expand single-stone moves outward from(1, 1, ..., 1). Great as an independent test oracle, though much slower and tied to tiny boards.
Follow-up questions
- If the board scaled to N x N with N^2 stones, what polynomial-time graph algorithm replaces backtracking? The problem becomes minimum-weight bipartite matching (pairing items between two equal-sized sets to minimize summed edge cost). With
ksurplus stones andkempty squares, running the Hungarian algorithm (a primal-dual assignment solver on ak x kcost matrix) takesO(k^3)time. Alternatively, formulate the board directly as a minimum-cost flow network (a directed graph with edge capacities and per-unit shipping costs where supply is routed to demand at minimum expense): wire a super-source to each cell havingcount > 1with capacitycount - 1and cost0, connect edge-adjacent board cells with infinite capacity and cost1, and wire each empty cell to a super-sink with capacity1and cost0. Pushingkunits of flow via successive shortest augmenting paths with Dijkstra runs inO(k * N^2 log N)time. - Why don't moving stones ever block each other or require detours longer than the Manhattan distance? Because intermediate squares have unlimited capacity, two stones never collide or deadlock in narrow passages, so any stone paired from
(r1, c1)to(r2, c2)can walk an unobstructed shortest grid path of|r1 - r2| + |c1 - c2|steps. Conversely, each legal step shifts a single stone's row or column by1, so no move sequence can beat the summed Manhattan distances of its net stone pairing, and by the triangle inequality (walking straight fromAtoEis never longer than relayingA -> MandM -> E) non-surplus stones never need to move at all. - How would you modify the solver to return a valid step-by-step list of adjacent transfers instead of just the move count? Have
fill_empty_cellsreturn(min_moves, best_pairs), wherebest_pairsrecords the winning((src_row, src_col), (target_row, target_col))pairings. Then replay each pair from start to finish one stone at a time: walk one stone vertically fromsrc_rowtotarget_rowand horizontally fromsrc_coltotarget_col, recording every single-cell hop(r1, c1) -> (r2, c2). Completing each trip in full is guaranteed valid in any pair order becausesrcstarts the trip with at least2stones and every intermediate square temporarily gains+1stone right before forwarding it onward.
Follow-up questions
- If the board scaled to N x N with N^2 stones, what polynomial-time graph algorithm replaces backtracking?
- Why don't moving stones ever block each other or require detours longer than the Manhattan distance?
- How would you modify the solver to return a valid step-by-step list of adjacent transfers instead of just the move count?
Similar questions
- Maximum Point Coverage by a Bounded-Perimeter Rectangle
- Fix and Extend a Nested Price Tracker
- Internal Corporate Knowledge Retrieval and Agent Platform
- Object-Oriented Pizza Order Pricing Pipeline
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger