Skip to main content
This tutorial shows how to build a complete Sudoku solver using Z3’s constraint solving capabilities. We’ll encode the rules of Sudoku as constraints and let Z3 find solutions.

Sudoku Rules

Sudoku is played on a 9x9 grid where:
  1. Each cell contains a number from 1 to 9
  2. Each row must contain all digits 1-9 with no repetition
  3. Each column must contain all digits 1-9 with no repetition
  4. Each 3x3 sub-grid must contain all digits 1-9 with no repetition
Let’s encode these rules as Z3 constraints.

Building the Solver

1

Set up the grid

Create a 9x9 grid of integer variables to represent the Sudoku board:
Each variable represents one cell in the Sudoku grid. The name cell_row_col helps identify each cell’s position.
2

Create solver and add range constraints

Every cell must contain a digit from 1 to 9:
3

Add row constraints

Each row must contain distinct values (all different):
Distinct() is a powerful Z3 constraint that ensures all its arguments have different values.
4

Add column constraints

Each column must contain distinct values:
5

Add 3x3 sub-grid constraints

Each 3x3 sub-grid must contain distinct values:
This iterates over the nine 3x3 boxes and ensures each contains distinct digits.
6

Add initial values (puzzle input)

For a specific puzzle, add constraints for the given cells:
7

Solve and display the result

Complete Working Example

Expected output:

Advanced: Miracle Sudoku

Miracle Sudoku adds special constraints on top of regular Sudoku rules:
  • Any two cells separated by a knight’s move (in chess) cannot contain the same digit
  • Any two cells separated by a king’s move cannot contain the same digit
  • Any two orthogonally adjacent cells cannot contain consecutive digits
Here’s how to add these constraints:
Miracle Sudoku can be solved with as few as 2 given digits due to the strong constraints.

Performance Tips

Int() variables are more efficient than Real() for discrete problems like Sudoku.
Add the most restrictive constraints first. This helps Z3 prune the search space faster.
For harder puzzles, you can use specific solver tactics:

Next Steps

Basic Solving

Review fundamental constraint solving concepts

Optimization

Learn how to find optimal solutions, not just feasible ones