Learn / Recursion and backtracking

Sudoku

Find an empty cell, try each digit that does not already appear in its row, column or 3 × 3 box, and recurse. If no digit fits, undo and go back. The first full board is the answer.

How to recognise it

  • A grid must be filled so that every row, column and region obeys a rule.
  • Only one solution is needed, so the search can stop at the first success.

The idea in one picture

Pencil in a digit, keep going, and when you get stuck, rub out the most recent guess and try the next digit there. A computer does this very fast, and the rules prune most guesses at once.

Template

function solve():
    find the first empty cell (r, c); if none: return true
    for d in 1..9:
        if d is not in row r, column c, or the box of (r, c):
            board[r][c] = d
            if solve(): return true
            board[r][c] = empty
    return false

Common mistakes

  • Checking the box with the wrong corner (use r / 3 * 3, c / 3 * 3).
  • Continuing to search after success and undoing the answer.
  • Forgetting to reset the cell to empty when every digit fails.

Problems

0 of 1 solved

Check yourself

Which 3 × 3 box holds cell (r, c)?

Why does the solver return as soon as solve() succeeds?

A common speed-up is to fill the empty cell with the fewest possible digits first. Why does it help?