Backtracking & Exhaustive Search · 15 min · free lesson

Sudoku Constraint Search: When to Use It

Recognise the problem shape before choosing Sudoku Constraint Search.

Core idea

The parent board state must be restored before trying another digit. State the input preconditions before applying this invariant.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Choose an empty cell, try allowed symbols, and undo; picking the fewest candidates prunes harder.

Exponential worst case · O(empty cells) depth294 execution steps
main · before line 25Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example inputrow0=53.678912

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 25
fn solve_sudoku(grid: &mut [[u8; 9]; 9]) -> bool {
    let empty = (0..9)
        .flat_map(|r| (0..9).map(move |c| (r, c)))
        .find(|&(r, c)| grid[r][c] == 0);
    let Some((r, c)) = empty else {
        return true;
    };
    for value in 1..=9 {
        let row = (0..9).all(|i| grid[r][i] != value);
        let col = (0..9).all(|i| grid[i][c] != value);
        let block = (r / 3 * 3..r / 3 * 3 + 3)
            .all(|a| (c / 3 * 3..c / 3 * 3 + 3).all(|b| grid[a][b] != value));
        if row && col && block {
            grid[r][c] = value;
            if solve_sudoku(grid) {
                return true;
            }
            grid[r][c] = 0;
        }
    }
    false
}
 
fn main() {
    let result = {
        let mut grid = [
            [5, 3, 0, 6, 7, 8, 9, 1, 2],
            [6, 7, 2, 1, 9, 5, 3, 4, 8],
            [1, 9, 8, 3, 4, 2, 5, 6, 7],
            [8, 5, 9, 7, 6, 1, 4, 2, 3],
            [4, 2, 6, 8, 5, 3, 7, 9, 1],
            [7, 1, 3, 9, 2, 4, 8, 5, 6],
            [9, 6, 1, 5, 3, 7, 2, 8, 4],
            [2, 8, 7, 4, 1, 9, 6, 3, 5],
            [3, 4, 5, 2, 8, 6, 1, 7, 9],
        ];
        assert!(solve_sudoku(&mut grid));
        grid[0][2].to_string()
    };
    println!("{result}");
}

Try your own version

Compare the visible input `row0=53.678912` with `row0=534.78912`. Predict why their results are `4` and `6`. Then change one legal value and explain whether the same invariant, the parent board state must be restored before trying another digit, still applies.

Open personal copy in Playground ↗

Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.

Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line. Borrowed or moved values are hidden when they cannot be inspected safely.
Five-panel Backtracking & Exhaustive Search infographic; panel 4 illustrates Sudoku.
Sudoku: follow panel 4 to see the operation, then trace this lesson's example.

Understand it

The first row 53.678912 lacks 4, and row, column and 3×3 block checks allow 4 in that hole. A board with many blanks needs more: the program tries an allowed digit, recurses, and resets the cell to zero when that branch fails, so another digit can be tried from the same parent board.

The worked program is a complete executable for this pattern. Its core function uses typed input so the state transitions remain visible. The challenge input contract is: Two input forms. row0=... is the first row of a valid solved board with one digit replaced by a dot: return that digit. board=... lists 81 cells row by row, with dots for blanks and exactly one solution: return the solved board as 81 digits. The visible fixture is row0=53.678912 and its example result is 4. The implementation and additional semantic fixtures were checked against an independent reference calculation. Those bounded tests establish these examples; they are not a proof for all inputs or a measurement on an iPhone.

Return a canonical String from solve: lowercase true/false for booleans; decimal integers without extra signs, leading zeros or whitespace; comma-separated sequence values and semicolon-separated groups. Whole-number medians have no decimal suffix; half medians use .5. Do not append a newline to the returned value. Preserve the explicitly named textual sentinels such as none or #. Input fixtures are bounded so the demonstrated arithmetic fits its named Rust types; satisfy the stated input preconditions before applying the algorithm.

String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

A problem is a good match for Sudoku Constraint Search when it asks for exact constraint completion. Here the concrete task is: Two input forms. row0=... is the first row of a valid solved board with one digit replaced by a dot: return that digit. board=... lists 81 cells row by row, with dots for blanks and exactly one solution: return the solved board as 81 digits. The visible input row0=53.678912 is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Use pruning when partial choices can already be ruled out. Meet-in-the-middle instead trades two exhaustive half-enumerations for a smaller search space. The right choice follows from those guarantees, not from a familiar noun in the prompt.

The decisive invariant is: Choose an empty cell, try allowed symbols, and undo; picking the fewest candidates prunes harder. Try to say why it applies to the task without quoting the implementation. Which fact becomes known after one update, and which possible answers remain? Most patterns here explore a decision tree; meet-in-the-middle instead enumerates two halves and combines them. Define the partial choice or subset summary that the pattern retains. If that claim cannot be maintained on a legal input, the pattern is wrong or one of its preconditions is missing. A counterexample is more useful than a vague warning: change one property of the sample, trace the first two steps, and identify the exact claim that fails.

Compare costs before committing. The advertised bound is Exponential worst case · O(empty cells) depth; identify the operation responsible for it and the extra memory it needs. Then compare a straightforward alternative: a direct scan, full sort, or repeated recomputation may be easier but can pay for the same work many times. Do not choose the more elaborate method just because it has a famous name. For the sample, predict 4 and explain which part of the state lets the method reach that result.

When the prompt is ambiguous, ask about input size, ordering, duplicates, and required output format. Test no solution, one solution, duplicate inputs, and the order in which candidates are tried if output order is observable. For recursive search, push a choice, recurse, then undo it; for meet-in-the-middle, collect each half before matching them. In Rust, clone a path only when storing a completed answer. The Rust sketch can show a useful primitive without proving that the whole task is solved; connect each primitive to the requested output. You should be able to name a fitting case, a near miss, and the assumption separating them before writing the first line.

The pattern

Choose an empty cell, try allowed symbols, and undo; picking the fewest candidates prunes harder.

When to use it: exact constraint completion

Complexity: Exponential worst case · O(empty cells) depth

Input: row0=53.678912

Read the code

fn solve_sudoku(grid: &mut [[u8; 9]; 9]) -> bool {
    let empty = (0..9)
        .flat_map(|r| (0..9).map(move |c| (r, c)))
        .find(|&(r, c)| grid[r][c] == 0);
    let Some((r, c)) = empty else {
        return true;
    };
    for value in 1..=9 {
        let row = (0..9).all(|i| grid[r][i] != value);
        let col = (0..9).all(|i| grid[i][c] != value);
        let block = (r / 3 * 3..r / 3 * 3 + 3)
            .all(|a| (c / 3 * 3..c / 3 * 3 + 3).all(|b| grid[a][b] != value));
        if row && col && block {
            grid[r][c] = value;
            if solve_sudoku(grid) {
                return true;
            }
            grid[r][c] = 0;
        }
    }
    false
}

fn main() {
    let result = {
        let mut grid = [
            [5, 3, 0, 6, 7, 8, 9, 1, 2],
            [6, 7, 2, 1, 9, 5, 3, 4, 8],
            [1, 9, 8, 3, 4, 2, 5, 6, 7],
            [8, 5, 9, 7, 6, 1, 4, 2, 3],
            [4, 2, 6, 8, 5, 3, 7, 9, 1],
            [7, 1, 3, 9, 2, 4, 8, 5, 6],
            [9, 6, 1, 5, 3, 7, 2, 8, 4],
            [2, 8, 7, 4, 1, 9, 6, 3, 5],
            [3, 4, 5, 2, 8, 6, 1, 7, 9],
        ];
        assert!(solve_sudoku(&mut grid));
        grid[0][2].to_string()
    };
    println!("{result}");
}

Complete std-only sudoku program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Try it

Compare the visible and independent fixtures. Explain the input assumption that makes this algorithm applicable, then identify a change that would invalidate it.

What success looks like: You can justify the choice from constraints rather than from a remembered problem title.

Check your understanding

Trace Sudoku Constraint Search on input row0=.34678912. Which result follows from the documented contract?

Reveal the answer
  1. 6
  2. 5
  3. 4

For this input the result is 5. The parent board state must be restored before trying another digit. Compare this independent fixture with the worked trace: The first row 53.678912 lacks 4, and row, column and 3×3 block checks allow 4 in that hole. A board with many blanks needs more: the program tries an allowed digit, recurses, and resets the cell to zero when that branch fails, so another digit can be tried from the same parent board.

Go deeper

Common misconception: “The reset marks a permanently solved cell”

The parent board state must be restored before trying another digit. The first row 53.678912 lacks 4, and row, column and 3×3 block checks allow 4 in that hole. A board with many blanks needs more: the program tries an allowed digit, recurses, and resets the cell to zero when that branch fails, so another digit can be tried from the same parent board.

  1. Concrete transition: The first row 53.678912 lacks 4, and row, column and 3×3 block checks allow 4 in that hole. A board with many blanks needs more: the program tries an allowed digit, recurses, and resets the cell to zero when that branch fails, so another digit can be tried from the same parent board.
  2. Independent second fixture: Input row0=.34678912 produces 5. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation.
  3. Boundary and contract: Input row0=534678.12 produces 9. The parent board state must be restored before trying another digit. The stated work bound is Exponential worst case · O(empty cells) depth. Count actual state changes; a successful output test alone does not prove that bound.

Transfer challenge: Compare the visible input row0=53.678912 with row0=534.78912. Predict why their results are 4 and 6. Then change one legal value and explain whether the same invariant, the parent board state must be restored before trying another digit, still applies.

Connections

  • Sudoku Constraint Search: Mental Model: Choose an empty cell, try allowed symbols, and undo; picking the fewest candidates prunes harder.
  • Challenge: Sudoku Constraint Search: Two input forms. row0=... is the first row of a valid solved board with one digit replaced by a dot: return that digit. board=... lists 81 cells row by row, with dots for blanks and exactly one solution: return the solved board as 81 digits.
Reveal the Algorithm Atlas answer

4

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Sudoku Constraint Search: When to Use It (courseId "algorithms", lessonId "algorithm.sudoku.recognize")
Link: https://crabrix.com/learn/algorithms/algorithm.sudoku.recognize
Goal: The parent board state must be restored before trying another digit. State the input preconditions before applying this invariant.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.sudoku.recognize) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.