Sudoku Rules
Sudoku is played on a 9x9 grid where:- Each cell contains a number from 1 to 9
- Each row must contain all digits 1-9 with no repetition
- Each column must contain all digits 1-9 with no repetition
- Each 3x3 sub-grid must contain all digits 1-9 with no repetition
Building the Solver
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.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.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.
Complete Working Example
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
Performance Tips
Use integer variables, not reals
Use integer variables, not reals
Int() variables are more efficient than Real() for discrete problems like Sudoku.Add constraints early
Add constraints early
Add the most restrictive constraints first. This helps Z3 prune the search space faster.
Consider solver tactics
Consider solver tactics
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
