← MAIN
04 // CONSTRAINT SATISFACTION

SUDOKU CSP

Watch three solvers fill a grid, one guess at a time.
SOLVER — GUESSES — BACKTRACKS — STATUS READY

HOW TO PLAY

The goal of a sudoku is to fill every empty square so that each row, each column and each 3×3 box holds the digits 1 to 9 once each. On this page the solvers do the filling, and the replay shows each step of their search.

Choose a puzzle with RANDOM or HARD, pick a solver, and press SOLVE + REPLAY. Cyan squares are guesses, purple digits are forced by propagation, and red squares are guesses that backtracking undid.

SKIP TO END jumps to the answer. RUN ALL THREE compares the three solvers on the puzzle on screen. A puzzle of your own can be typed under MORE SETTINGS.

SEARCH REPLAY 0 / 0
guess forced by propagation backtrack
COMPARE SOLVERS ON THIS PUZZLE
SolverStatusGuessesBacktracksGuesses (log scale)Time
PUZZLE
—
SOLVER
More settings
CUSTOM (81 digits, 0 or . for empty)
REPLAY SPEED: 40 STEPS / SECOND

HOW IT WORKS

A constraint satisfaction problem (CSP) is a set of variables, each with a set of allowed values called its domain, together with constraints that restrict which values may be used together. A sudoku is a CSP: its 81 squares are the variables, the digits 1 to 9 are the domains, and the rule that the nine squares of each row, column and box hold different digits is the constraint. The three solvers on this page are search programs, not learned models. Each one fills the empty squares one at a time, guessing a digit and undoing the guess (backtracking) when the guess leads to a contradiction. They differ in the order in which they fill squares and in how much they deduce before guessing. A guess is one digit tried in one square, so the guess count measures the wasted work.

Sudoku as a CSP

Two squares are peers when they share a row, a column or a box. The 27 units are the nine rows, the nine columns and the nine boxes. Every square lies in three units and has 20 peers. The solver tables are built from these lists1. A square's legal digits are the digits that none of its peers holds2.

L(i) = \{\, d \in \{1,\dots,9\} : d \notin \{\, c_j : j \in P(i) \,\} \,\}
2

Here i is a square, P(i) is its 20 peers, c_j is the digit in peer j (0 when that peer is empty), and L(i) is the set of legal digits. A 0 never equals a digit from 1 to 9, so empty peers remove nothing. The code keeps the peers' digits as one 10-bit mask, in which bit d is set when digit d is used. Empty peers set bit 0, which is never tested. One pass over the peers builds the mask, and one test per digit reads off the legal digits. Example. If a square's row holds 5 and 9, its column holds 2, and its box holds 1, then L(i) = \{3, 4, 6, 7, 8\}.

Plain backtracking

Backtracking is a depth-first search over partial fillings. It places a digit in the next empty square, recurses on the rest, and removes the digit again if the recursion fails. Plain backtracking visits the empty squares in reading order (row by row, from the top left) and tries the legal digits in ascending order. It has no lookahead and no ordering, so it can explore a long dead end before it notices the contradiction.

Each digit placed is one guess, and each digit removed is one backtrack3. The benchmark caps a run at 2,000,000 guesses4. Within that cap, plain backtracking solved 198 of the 200 generated puzzles, with a mean of 119,468 guesses. The means include the runs that hit the cap. The server stops any solver at 200,000 guesses5, so a run that reaches that limit ends with the status limit.

6
function SOLVE-PLAIN(board, k):                  # k is the index of the next empty square
    if k = number of empty squares:
        return true                              # every square is filled
    i ← the empty square number k, in reading order
    for each digit d in LEGAL-DIGITS(board, i):  # the digits 1 to 9 that no peer holds
        board[i] ← d
        if SOLVE-PLAIN(board, k + 1):
            return true
        board[i] ← 0                             # undo the guess
    return false                                 # no digit fits: back up

Givens. The clues in the starting puzzle are its givens. GIVENS-CONSISTENT rejects a puzzle whose givens already repeat a digit in a unit, since no grid can satisfy it, so the search returns at once.

Trace. RECORD writes each guess and each undo to a list of events, up to the trace limit (20,000 events on the server7), so that the page can replay the search. Stopping the list at a fixed length keeps long runs small.

Guess limit. The count is checked as each guess is made. When it passes the limit, the raise jumps out of the recursion to the handler, which returns the status limit. A hopeless run therefore stops after a bounded amount of work.

MRV and forward checking

MRV (minimum remaining values) is a rule for choosing the next square: take the empty square with the fewest legal digits. That square is the most likely to be a dead end, so trying it first exposes a mistake sooner. The scan stops early at a square with at most one legal digit, because no later square can beat it. A square with no legal digit is also chosen, and the search then backs up at once.

i^{*} = \operatorname*{arg\,min}_{\,i \,:\, c_i = 0} \; |L(i)|
8

Here c_i = 0 marks an empty square, |L(i)| is the number of its legal digits, and i^{*} is the square chosen. Ties go to the lowest index, because the scan replaces the best square only when a count is strictly smaller.

Forward checking looks one step ahead after each placement. After a digit goes into a square, the solver checks each of its peers. If an empty peer is left with no legal digit, the placement is undone at once, and the search never goes below it. This is the default solver on this page9 and on the server10.

\text{FC}(i) = \bigwedge_{j \in P(i)} \bigl( c_j \neq 0 \;\lor\; L(j) \neq \varnothing \bigr)
11

Here \text{FC}(i) is true when every peer of square i is either filled or still has a legal digit. The test runs over all 20 peers, and a filled peer always passes it. The solver keeps the placement only while \text{FC}(i) holds.

12
function MRV-FC(board):
    if no square is empty:
        return true                              # the grid is full
    i ← the empty square with the fewest legal digits
    for each digit d in LEGAL-DIGITS(board, i):
        board[i] ← d
        if FORWARD-CHECK(board, i) and MRV-FC(board):
            return true
        board[i] ← 0                             # undo the guess
    return false

Early stop in MRV. Forward checking keeps every empty square at one or more legal digits, so a square with one digit is the smallest count the scan can usefully find, and the scan stops there. The exception is a puzzle that is already dead at the start. The search still rejects it, only later.

Forward check. FORWARD-CHECK runs after the placement and before the recursion, so a placement that leaves a peer with no digit is undone without extending the search below it. Its undo is recorded in the trace like any other backtrack.

Constraint propagation

Constraint propagation removes digits that cannot appear in any solution, and fills the squares that are forced, before the solver guesses again. Each square's candidates are stored as a bitmask, a binary number in which bit d is set when digit d is still possible. Bit 0 is never used, so the full set of candidates is the mask below.

\text{ALL} = \sum_{d=1}^{9} 2^{d} = 1022
13

\text{ALL} is the mask that allows every digit, and the code writes it as 0x3FE. A square set to digit d has the mask 2^{d}. A mask is a single when exactly one of its bits is set. The code tests this without a loop, because D \,\&\, (D-1) clears the lowest set bit of D. The result is zero exactly when D has at most one bit set, and the test is written as the following condition.

|D| = 1 \iff D \neq 0 \;\land\; D \,\&\, (D-1) = 0
14

Here D is a square's mask, \& is bitwise AND, and |D| is the number of bits set. The code skips any square where D \,\&\, (D-1) is not zero, because such a square is not a single yet.

Two rules are applied. A naked single is a square whose mask is a single, and its digit is removed from every peer. A hidden single is a digit that fits in only one square of a unit, and that square must take the digit. Every square whose mask changes goes onto a queue, and the queue is emptied. The rules therefore run to a fixed point, the state in which no rule changes anything. An empty mask, or a digit with no place left in a unit, shows that the state is contradictory.

D(j) \leftarrow D(j) \,\&\, \lnot\, 2^{d} \quad \text{for each peer } j \text{ of } i, \text{ when } D(i) = 2^{d}
15

Here D(i) is the mask of the naked single i, and \lnot is bitwise NOT. Clearing bit d removes digit d from peer j. A peer whose mask becomes empty means the state is contradictory, and a peer whose mask becomes a single joins the queue.

\begin{aligned} P_{u,d} &= \{\, j \in u : d \in D(j) \,\} \\ |P_{u,d}| = 1 &\;\Rightarrow\; D(j) \leftarrow \{d\} \text{ for the one } j \in P_{u,d} \end{aligned}
16

Here u is a unit, and P_{u,d} is the set of squares in u that can still take digit d. The code checks all nine digits in each of the three units that contain the square just fixed. Only those units need the check: the fixed square removes digits only from its peers, and every peer shares one of those units with it. A square set by a hidden single is itself queued, so its own units are checked later. Example. If digit 7 can go only in column 4 of a row, the square in column 4 is forced to 7, even when it still had several candidates.

17
function SOLVE(domains):                         # one candidate mask per square
    if not PROPAGATE(domains, the givens):
        return fail
    return SEARCH(domains)

function SEARCH(domains):
    i ← the undecided square with the fewest candidates
    if there is no undecided square:
        return domains                           # every square has one candidate
    for each digit d in domains[i]:
        trial ← copy of domains with domains[i] ← {d}
        if PROPAGATE(trial, [i]):
            solved ← SEARCH(trial)
            if solved is not fail:
                return solved
    return fail

Queue. The queue holds the squares whose masks changed, and the code takes the last one, so the work is depth-first. A square that is popped while its mask still has two or more bits is skipped, since only singles fire the rules.

Copies. Each guess works on a copy of the masks, so a failed branch leaves the parent's masks unchanged. Forced fills are recorded as propagate events. They are not counted as guesses, and the replay shows them in purple.

When propagation stops with undecided squares left, the solver guesses. It picks the undecided square with the fewest candidates (the MRV rule, applied to masks with two or more bits), tries each candidate in turn, and runs propagation again after each guess. Averaged over the 200 generated puzzles, constraint propagation needed 7 guesses. Thirty of those puzzles needed no guess at all, because propagation alone solved them18.

Generated and hard puzzles

The generator19 starts from a complete grid, then removes clues one at a time in random order. A removal is kept only if the puzzle still has exactly one solution. The uniqueness test is COUNT-SOLUTIONS20, which stops after it finds two solutions, so it returns 0, 1 or 2.

The complete grid is a shuffled copy of a base pattern21. In the base pattern, the digit index in row r and column c is (3(r \bmod 3) + \lfloor r/3 \rfloor + c) \bmod 9. The row order keeps each band of three rows together, the column order keeps each stack of three columns together, and the digits are relabelled by a random permutation.

S_{9a+b} = \pi\bigl( (3(r_a \bmod 3) + \lfloor r_a/3 \rfloor + c_b) \bmod 9 \bigr)
22

Here S_{9a+b} is the square in row a and column b of the finished grid, counting from 0. r_a and c_b are the base rows and columns that the shuffled orders place at positions a and b. \pi is a random permutation of the digits 1 to 9, and \pi(k) is the digit at index k.

\text{keep the removal of clue } i \iff \min(N,\,2) = 1
23

Here N is the number of solutions of the puzzle after the removal, and \min(N,\,2) is the value that COUNT-SOLUTIONS returns, since it stops at 2. A clue is restored whenever this count is not 1. The finished puzzle is minimal: a clue that was needed when it was tested stays needed, because removing further clues can only add solutions.

Difficulty is the number of guesses the propagation solver needs for the puzzle24. The committed set has 200 puzzles, generated with seed 02526. They have 21 to 28 clues, 24.3 on average, and a mean difficulty of 7 guesses.

Hard puzzles. The benchmark also uses four well-known hard puzzles27. Their keys are inkala_2012, which is the 2012 puzzle by Arto Inkala, ai_escargot, norvig_hard1 and platinum_blonde. Each was published by its author.

19
function MAKE-PUZZLE():
    solution ← a random complete grid
    puzzle ← copy of solution
    for each square i in random order:
        remove the clue at i
        if the puzzle does not have exactly one solution:
            put the clue back
    return puzzle, solution

Random order. Each square is tried once, in a random order, so the removals do not follow the board.

Shuffled groups. SHUFFLED-GROUPS draws the order of the three bands and, for each band, a fresh order of its three rows. The same function is used for columns, so the shuffled grid keeps the band and stack structure of the base pattern.

20
function COUNT-SOLUTIONS(board, limit):
    found ← 0
    function SEARCH(domains):
        i ← the undecided square with the fewest candidates
        if there is none:
            found ← found + 1                    # a complete grid
            return
        for each digit d in domains[i]:
            if found < limit:
                trial ← copy of domains with domains[i] ← {d}
                if PROPAGATE(trial, [i]):        # naked and hidden singles
                    SEARCH(trial)
    if PROPAGATE(candidates from board, its clues):
        SEARCH(candidates from board)
    return found

Stopping early. Once \text{found} reaches the limit, the loops stop trying new digits, so the search ends soon after the second solution. A complete grid adds one to the count, and a contradiction returns without adding to it.

Heuristics and their values

HeuristicWhat it measuresValue / weight
MRVNumber of legal digits left in each empty square. The square with the fewest is chosen next.None. It is a rule for picking the next square, not a score.
Forward checkingWhether every empty peer still has a legal digit after a placement.None. The placement is kept or undone.
Naked singleA square with only one candidate digit.None. The digit is forced.
Hidden singleA digit that fits in only one square of a row, column or box.None. The digit is forced there.

None of these heuristics has a numeric weight. They are standard constraint-satisfaction techniques, fixed in the code, so there is no tuning run to report.

Benchmark results

Benchmark28 on 200 generated puzzles: plain backtracking had a mean of 119,468 guesses (198 solved), MRV with forward checking 364 (200 solved), and constraint propagation 7 (200 solved). On the four hard puzzles, plain backtracking solved 3 of 4 (mean 781,593 guesses), MRV with forward checking 4 of 4 (mean 865), and constraint propagation 4 of 4 (mean 44). These runs used the benchmark cap of 2,000,000 guesses. A run that hit the cap contributes its capped count to the mean, so a mean for plain backtracking is a lower bound on its true cost.

The server stops any solver at 200,000 guesses5, so plain backtracking can fail on the hard puzzles here. The other two solvers finished all four hard puzzles well inside that cap.