Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithm · Backtracking

Guess, Hit a Wall, Erase.

Don't memorize the Sudoku solver — watch it guess, hit a wall and erase. Scan for the first empty cell, try each digit that is legal in its row, column and box, place it and recurse. When a cell has no legal digit, that is the signal: an earlier choice was wrong, so backtrack — undo the last placement and try the next. Same push-recurse-pop skeleton as subsets and combination sum, now steered by constraints.

first empty cell · legal in row + col + box · place & recurse · no digit → backtrack
CELL SCAN

Find the first empty cell in row-major order — the next decision to make.

CANDIDATES

Try digits 1..k in order; keep only ones legal for this cell.

CONSTRAINTS

A digit is legal only if unused in its row, its column and its 2×2 box.

BACKTRACK

No legal digit here? Erase the last placement and try the next candidate there.

sudoku.sim — 4×4 board, digits 1–4, four 2×2 boxes
Ready

Two clues are locked (grey). Press Step: the solver scans for the first empty cell, tries the lowest legal digit, and recurses — until a cell has no legal digit, where it must erase and back up.

legal(d) = d not in row ∧ not in col ∧ not in box
2
Cells filled
0
Backtracks

Constraints turn guessing into search

Subsets branched freely; combination sum added a bound; Sudoku adds a full set of constraints, and that is what makes it a genuine constraint-satisfaction problem. The solver is still the same depth-first walk — pick the next undecided thing, try a value, recurse, undo on failure — but now every value must pass three tests at once: it cannot repeat in the cell's row, its column, or its 2×2 box. Those tests are the pruning. Most digits are rejected instantly, so the branching factor collapses far below the naive four-choices-per-cell. The dramatic moments are the backtracks: the solver commits to a digit, fills several more cells on top of it, then discovers a cell with nothing legal left — proof that the earlier commitment was wrong. It rewinds, erasing as it goes, and tries the next option.

01

Scan for an empty cell

Row-major search for the first blank. If none remain, the board is solved.

02

Filter by constraints

For digits 1..k, keep only those absent from the cell's row, column and box.

03

Place and recurse

Write the first legal digit and recurse to the next empty cell.

04

Backtrack on a dead end

If a cell has no legal digit, return and erase the previous placement; try its next candidate.

Board
4×4 demo
Time
O(k^m)
Space
O(1)
Pattern
CSP + BT

A real 9×9 board works identically: digits 1–9, nine 3×3 boxes, the same scan-try-recurse-erase loop. The worst case is exponential — O(k^m) for m empty cells — but constraints keep the real search tiny, and heuristics shrink it further: fill the most-constrained cell first (minimum remaining values), propagate forced digits before guessing, and store each row, column and box as a bitmask so legality is one bitwise test. The backtracking core, though, is exactly what you just watched.

Check yourself

1 · What triggers a backtrack?

If every digit conflicts with the row, column or box, the cell is unsolvable given the current choices — so the solver erases the previous placement and tries again.

2 · A digit is legal in a cell only if it is unused in the cell's…

All three constraints must hold simultaneously: no repeat in the row, the column, or the box that contains the cell.

3 · Why is Sudoku called a constraint-satisfaction problem?

A solution is an assignment to every cell that violates no row, column or box constraint — backtracking searches assignments and rejects illegal ones early.

The picture: one cell, three filters

Cell: row 1, column 3 (a blank)row 1357column 38top-left box35689legal123456789a digit survives only if it is blocked in none of the three: 1, 2, 4
The first blank of the 9×9 puzzle in the runner. Its row holds 3, 5, 7, its column 8, its box 3, 5, 6, 8, 9. In the first three rows a red square marks a digit that line already holds; in the bottom row the highlighted digits are what the solver may try, in order. Every placement in the search starts from a filter like this one.

Worked example, step by step

The 9×9 puzzle from the runner has 51 blanks. The solver below scans in row-major order and tries candidates in increasing order. These are the first 12 of its many moves; cells are written (row, column) counting from 1.

StepCellLegal digitsActionNote
1(1, 3)1, 2, 4place 1first untried
2(1, 4)2, 6place 2first untried
3(1, 6)4, 6, 8place 4first untried
4(1, 7)8, 9place 8first untried
5(1, 8)9place 9only choice
6(1, 9)none leftdead endreturn failure to the caller
7(1, 8)—erase 9try the next candidate, if any
8(1, 8)none leftdead endreturn failure to the caller
9(1, 7)—erase 8try the next candidate, if any
10(1, 7)8, 9place 9first untried
11(1, 8)none leftdead endreturn failure to the caller
12(1, 7)—erase 9try the next candidate, if any

The first dead end arrives at step 6. The solver has committed to (1, 3) = 1, (1, 4) = 2, (1, 6) = 4, (1, 7) = 8, (1, 8) = 9, and cell (1, 9) has no digit left. Notice what that proves: nothing about cell (1, 9) is wrong, only the choices above it, so the solver goes back one step at a time and retries. The whole run makes 4209 recursive calls and erases 4157 placements before it finds the solution. Most of that work sits in the top row, because a bad early choice is only discovered several cells later. Picking a cell with the fewest legal digits instead of the first blank, same filter, finishes the same puzzle in 52 calls and 0 erasures.

Complexity and trade-offs

CaseTimeSpaceWhy
Brute force: fill, then checkO(9m)O(m)With m = 51 blanks that is about 4.6 × 1048 grids. Not run, just counted.
Backtracking, first blankO(9m) worstO(m) stackSame bound, far smaller in practice: 4209 calls on this puzzle, since each placement is checked before recursing.
Backtracking, fewest candidates firstsame worst caseO(m)52 calls and 0 erasures here. Costs a scan of every blank per step.
Singles propagation aloneO(m²) per sweepO(1)Repeatedly fill any cell with exactly one legal digit. On this puzzle it leaves 0 blanks. On harder ones it stalls and you must guess.
Bitmask legality testsame node countO(1) extraKeep one 9-bit mask each for rows, columns and boxes. A candidate set becomes an OR and a NOT instead of a 27-cell scan.

The worst case never changes: it is exponential in the number of blanks, and Sudoku generalised to n×n grids is NP-complete. What changes is how often a real puzzle gets near it. Move ordering gave 4209 calls versus 52 here, a factor of 81, with no change to correctness. Space is the stack depth, at most one frame per blank, plus the board itself.

Common mistakes

  • Not erasing the cell on failure

    If a failed digit is left in the grid, later cells see it as a given. On the page’s puzzle the solver without the reset gives up after 25 calls and reports no solution, although one exists. Set the cell back to 0 before trying the next digit.

  • Checking row and column but not the box

    Dropping the box test makes the search far looser, and it still “succeeds”. On the page’s puzzle it makes 249819 calls and returns a full grid that breaks the box rule. A solver that ends is not necessarily a solver that is right; validate the output once.

  • A wrong box origin

    The top-left corner of a cell’s box is 3 * (r // 3), 3 * (c // 3). Using 3 * (r % 3) picks a different box for most cells; on the page’s puzzle the solver then reports no solution after 22 calls, because the true digits look blocked.

  • Solving in place

    The runner asks for a solved copy. A version that fills the caller’s array leaves it with 0 blanks instead of 51 after it succeeds, so the original puzzle can no longer be shown, reset or checked for uniqueness.

  • Stopping at the first solution when you needed to know there is only one

    Puzzle setters need uniqueness. Continuing the search after the first answer shows the page’s puzzle has exactly 1 solution, found in 4632 calls. A solver that returns early cannot tell you that.

Where this shows up

  • Scheduling and timetabling

    Assign each lesson, shift or exam a slot so that no two conflicting items share one. The unknowns, the allowed values and the pairwise conflicts are the same three parts as cells, digits and row/column/box rules.

  • Puzzle generation

    Generators remove digits from a full grid and re-solve, counting solutions after each removal, and keep a removal only if the puzzle still has exactly one. The solution counter is the solver with the early return deleted, as in the uniqueness check above.

  • Search with propagation

    Real constraint solvers interleave the two ideas: propagate forced choices first, guess only when stuck, and undo propagation on backtrack. Here singles alone clear every blank (0 left), so no guessing is needed.

  • Same engine, other problems

    N-Queens, graph colouring, word placement in a crossword and combination search all share the loop: pick a variable, try its legal values, recurse, undo. Only the legality test is rewritten.

SOLVE IT YOURSELF

Solve it: fill the grid by backtracking

Brute force would try 9⁸¹ grids. Checking each placement against its row, column and box before recursing prunes almost all of them — a real puzzle falls in milliseconds. Python or TypeScript.

YOUR TASK

Implement solve(board): a 9×9 grid of digits with 0 for blanks. Return a solved copy, or None (null) if the puzzle has no solution. Do not mutate the input.

HINTS — 7 IDEAS
  1. Find the first blank cell. If there are none, the grid is complete — you are done.
  2. Try digits 1–9. Place one only if it does not already appear in that row, column, or 3×3 box.
  3. Recurse. If the recursive call succeeds, propagate success straight up.
  4. If it fails, reset the cell to 0 and try the next digit. Forgetting the reset leaves stale digits that poison every later branch.
  5. If no digit works, return failure — that unwinds one level and lets the caller try its next digit.
  6. The box origin is 3·(r//3), 3·(c//3) — integer division snapping to the top-left corner of the containing box.
  7. Validity-checking before recursing is the entire optimisation. Placing blindly and checking at the end is what makes the naive version astronomically slow.
CPython · WebAssembly

Questions

Why show a 4×4 board instead of 9×9?

The algorithm is identical; a 4×4 grid (digits 1–4, 2×2 boxes) is simply legible when animated. On 9×9 you swap in digits 1–9 and 3×3 boxes and run the exact same scan-try-recurse-erase loop.

How do real solvers get so fast?

Three tricks: the minimum-remaining-values heuristic fills the most-constrained cell first; constraint propagation fills forced cells before any guessing; and bitmasks for each row, column and box make the legality check a single bitwise AND. The exponential worst case rarely shows up on real puzzles.

Is this the same as N-Queens?

Yes, structurally. Both are constraint backtracking: place, check constraints, recurse, undo on failure. N-Queens constrains by attacked squares; Sudoku by row, column and box. Change the constraint check and the same engine solves a different puzzle.

The same engine, one more constraint.

Scan, try a legal digit, recurse, and erase on a dead end. Choices became bounds became constraints — that is the whole backtracking arc.

Finished this one? 0 / 99 Algorithms done

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms