Sub topic 12
Solving Sudoku as a Constraint Satisfaction Problem
This chapter assumes you have worked through the earlier chapters on the choose-explore-unchoose template, state restoration, pruning, and N-Queens. You should be comfortable reading recursive Python that mutates shared state and undoes the change on return. Sudoku uses the same machinery as N-Queens. The new part is the vocabulary: Sudoku is a standard example of a constraint satisfaction problem (CSP). Seeing it as a CSP gives you a general recipe you can reuse for scheduling, timetabling, map coloring, and many puzzles.
What Makes a Problem a CSP
A constraint satisfaction problem has three parts:
- Variables: the unknowns you must assign.
- Domains: the set of values each variable may take.
- Constraints: rules that restrict which combinations of values are allowed.
A solution assigns a value to every variable so that no constraint is violated. Backtracking solves a CSP by assigning one variable at a time and checking constraints after each assignment. If a partial assignment already breaks a constraint, no completion of it can be valid, so the branch is pruned.
The table below maps these terms onto Sudoku and onto N-Queens from the previous chapter.
| CSP term | Sudoku | N-Queens |
|---|---|---|
| Variables | Each empty cell of the 9×9 grid | The column of the queen in each row |
| Domain | Digits 1 to 9 | Columns 0 to n−1 |
| Constraints | Each row, column, and 3×3 box holds each digit at most once | No two queens share a column or diagonal |
| Goal | Fill every empty cell | Place a queen in every row |
| Pre-assigned values | The given clues | None |
Sudoku has 27 constraint groups: 9 rows, 9 columns, and 9 boxes. Each group says "all values here are different," which is called an all-different constraint. Every cell belongs to exactly three groups, so it shares a constraint with 20 other cells, called its peers: 8 in its row, 8 in its column, and 4 more in its box that are not already counted.
The Search Loop
The solver uses the template you already know. It finds the first empty cell, tries each digit that does not break a constraint, recurses, and undoes the placement if the recursion fails.
A Direct Implementation
This version scans the grid for each constraint check. It is short and easy to verify.
def is_valid(board, r, c, v):
if any(board[r][j] == v for j in range(9)):
return False
if any(board[i][c] == v for i in range(9)):
return False
br, bc = 3 * (r // 3), 3 * (c // 3)
return all(board[i][j] != v
for i in range(br, br + 3)
for j in range(bc, bc + 3))
def solve(board):
# board is a 9x9 list of lists; 0 marks an empty cell.
for r in range(9):
for c in range(9):
if board[r][c] == 0:
for v in range(1, 10):
if is_valid(board, r, c, v):
board[r][c] = v
if solve(board):
return True
board[r][c] = 0
return False # no digit fits this cell
return True # no empty cells remain
puzzle = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9],
]
if solve(puzzle):
for row in puzzle:
print(row)
# [5, 3, 4, 6, 7, 8, 9, 1, 2]
# [6, 7, 2, 1, 9, 5, 3, 4, 8]
# ...Two details control correctness.
The return False sits after the digit loop and inside the if board[r][c] == 0 branch. The function only looks at the first empty cell it finds. If none of the nine digits works there, the current partial grid cannot be completed, and the function reports failure right away. It does not move on to later cells. Skipping a cell would leave it empty forever, and the solver could then wrongly report success.
The return True at the bottom runs only when the loops finish without finding an empty cell. That is the base case: every variable has a value, and each value passed its check when it was placed.
Faster Constraint Checks with Sets
Each is_valid call reads 27 cells, and solve rescans the grid from the top on every call. The N-Queens chapter fixed the same problem by keeping sets of occupied columns and diagonals. Sudoku uses the same idea: keep one set per row, per column, and per box, and update all three on every choose and unchoose.
def solve_fast(board):
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
boxes = [set() for _ in range(9)]
empties = []
for r in range(9):
for c in range(9):
v = board[r][c]
if v == 0:
empties.append((r, c))
continue
b = 3 * (r // 3) + c // 3
if v in rows[r] or v in cols[c] or v in boxes[b]:
return False # the givens already conflict
rows[r].add(v)
cols[c].add(v)
boxes[b].add(v)
def backtrack(k):
if k == len(empties):
return True
r, c = empties[k]
b = 3 * (r // 3) + c // 3
for v in range(1, 10):
if v in rows[r] or v in cols[c] or v in boxes[b]:
continue
board[r][c] = v
rows[r].add(v)
cols[c].add(v)
boxes[b].add(v)
if backtrack(k + 1):
return True
board[r][c] = 0
rows[r].remove(v)
cols[c].remove(v)
boxes[b].remove(v)
return False
return backtrack(0)
puzzle = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9],
]
print(solve_fast(puzzle)) # True
print(puzzle[0]) # [5, 3, 4, 6, 7, 8, 9, 1, 2]This version changes three things:
- Constant-time checks. Each check is three set lookups instead of a scan of 27 cells.
- A precomputed variable list.
emptiesfixes the order of the variables, and the indexkreplaces the grid rescan. The recursion depth equals the number of empty cells, at most 81, which is well within Python's default limit. - Input validation. The direct version trusts the givens. If two clues already clash, it searches the entire tree before it fails. The set version catches the clash while it loads the board and returns immediately.
The box index 3 * (r // 3) + c // 3 numbers the boxes 0 to 8 from left to right and top to bottom. If you write r // 3 + c // 3 instead, several boxes share an index, which is a subtle bug: the solver then rejects valid digits and may find no solution at all.
Behavior and Edge Cases
| Situation | What the solver does |
|---|---|
| Well-formed puzzle with one solution | Fills the board in place and returns `True` |
| Puzzle with several solutions | Returns the first one in search order and does not report the others |
| Contradictory givens | `solve` searches until it exhausts the tree, then returns `False`. `solve_fast` returns `False` during setup |
| Puzzle with no solution but valid givens | Both return `False`, and every cell they filled has been reset to 0 |
| Empty board | Finds a valid completed grid quickly, because few constraints are active early |
The board is modified in place. If the caller needs the original puzzle, pass [row[:] for row in puzzle]. On failure, the state restoration guarantees the board comes back exactly as it went in. That follows from undoing every placement, the same property you relied on in the word-search chapter.
Why Plain Backtracking Is Enough Here
The worst-case bound looks frightening. With m empty cells, the tree has at most 9^m leaves, and a typical puzzle has around 50 to 60 empty cells. In practice, the constraints prune most branches within a few levels, because each placed digit removes options from 20 peers. Newspaper puzzles usually solve in milliseconds with solve_fast. Some puzzles are built specifically to defeat naive row-major search and can take seconds or longer. Those are the cases where the heuristics from the next chapter pay off.
Exercise
Modify solve_fast so it counts solutions, stopping once it has found 2, and returns the count. A proper Sudoku has exactly one solution. What must change in backtrack?
Show answer
Make backtrack return a count instead of a boolean. At the base case return 1. In the loop, add the result of backtrack(k + 1) to a running total, always undo the placement (do not return early on success), and break out once the total reaches 2. Return the total. Because the board is reset after every placement, it ends up unchanged, so you need to copy it at the base case if you also want the solution.
Exercise
In the direct solve function, the base case is return True after both loops finish. Why is it safe to declare success without re-checking the whole grid?
Show answer
A digit is placed only after is_valid confirms it does not clash with any value already in its row, column, or box, and the givens are assumed consistent. Every constraint between two filled cells was therefore checked when the later of the two was placed. Once no empty cells remain, every pair has been checked and the grid is valid.
Exercise
Express 4-coloring of a map of countries as a CSP using the same three parts as the Sudoku table. Which part of the Sudoku solver would change?
Show answer
The variables are the countries, the domain is the four colors, and the constraints say that neighboring countries get different colors. The search loop stays the same. Only the validity check changes: instead of row, column, and box sets, check the chosen color against the colors already assigned to the country's neighbors.