Sub topic 12
Solving Sudoku as a Constraint Satisfaction Problem
This chapter assumes you know the choose-explore-unchoose template, how to restore state after a recursive call, and the pruning ideas from the N-Queens chapter. Sudoku reuses that machinery on a fixed 9x9 board.
Sudoku in CSP terms
A constraint satisfaction problem (CSP) has three parts:
| CSP part | In Sudoku |
|---|---|
| Variables | The 81 cells, of which the empty ones still need values |
| Domains | The digits 1 to 9 for each empty cell |
| Constraints | No digit repeats in any row, column, or 3x3 box |
Backtracking solves a CSP by assigning one variable at a time. After each assignment it checks the constraints and undoes the assignment if it causes a conflict. N-Queens works the same way: there each row is a variable and its domain is the set of columns. Sudoku differs in two ways. The givens fix some variables before the search starts, and the solver stops at the first complete assignment instead of counting every solution.
The solver
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)
# First line printed: [5, 3, 4, 6, 7, 8, 9, 1, 2]Each call finds the first empty cell and tries every digit that passes is_valid. The template's steps map onto the code like this:
- Choose:
board[r][c] = v. - Explore: the recursive
solve(board). - Unchoose:
board[r][c] = 0.
If no digit works, the call returns False. That signal makes the caller try its own next digit.
Common errors
- Forgetting the reset. If the code skips
board[r][c] = 0, a failed digit stays on the board. Deeper calls then treat that cell as a given. - Returning
Truetoo early. The code must returnTrueonly when the scan finds no empty cell, or when a recursive call has already succeeded. - Leaving out
return Falseafter the digit loop. Without it, the function keeps scanning past a dead cell and can report a partial board as solved. - Mutation surprises.
solvechanges the board in place. Passcopy.deepcopy(puzzle)if you need to keep the original.
Exercise
Suppose the line board[r][c] = 0 is deleted and every digit fails at some cell. What state is that cell left in, and why does this break the search?
Show answer
The cell keeps the last digit that passed is_valid, even though no solution below it was found. The function returns False, the caller tries its next digit, and deeper calls scan the board and skip this cell as if it were filled. Constraint checks then run against a value that was never part of a valid solution. The solver can miss real solutions or report that none exist.
Exercise
is_valid scans 27 cells on every call. Describe a way to make each check run in constant time.
Show answer
Keep three arrays of sets, rows[9], cols[9], and boxes[9], where the box index is 3 * (r // 3) + c // 3. Fill them from the givens before the search starts. Checking a digit becomes three set lookups. When you place a digit, add it to all three sets, and remove it when you undo the placement. This is the same idea N-Queens uses with its column and diagonal sets.