Sub topic 14
Ordering Heuristics and Forward Checking
This chapter assumes you have read the Sudoku chapter and the chapter on analyzing the cost of backtracking. You should be comfortable with the is_valid and solve functions shown there.
Why Order Matters
Plain backtracking takes choices in a fixed order. The Sudoku solver fills the first empty cell it finds and tries digits 1 through 9. That works, but the order you choose in can change the size of the state-space tree by orders of magnitude. The tree holds the same solutions either way. A bad order just makes you discover dead ends deep in the tree instead of near the root.
There are two separate decisions:
| Decision | Question | Common heuristic |
|---|---|---|
| Variable ordering | Which unfilled slot do I branch on next? | Minimum remaining values (MRV): pick the slot with the fewest legal options |
| Value ordering | Which option do I try first in that slot? | Least constraining value: try the option that rules out the fewest options for neighbors |
| Forward checking | Can I tell early that this branch is dead? | After each choice, fail as soon as any slot has no legal options left |
MRV is sometimes called "fail first." If a cell has only one legal digit, branching on it costs nothing. If a cell has zero legal digits, the current branch is already dead. MRV finds that immediately instead of after filling twenty other cells.
Forward Checking
Forward checking looks one step ahead. After you make a choice, it checks the remaining domain of every unfilled slot, meaning the set of options still legal for that slot. If any domain is empty, you undo the choice right away. This is pruning applied to the whole board, not just to the cell you are filling.
A Sudoku Solver with MRV and Forward Checking
def candidates(board, r, c):
used = set(board[r]) | {board[i][c] for i in range(9)}
br, bc = 3 * (r // 3), 3 * (c // 3)
used |= {board[i][j] for i in range(br, br + 3) for j in range(bc, bc + 3)}
return [v for v in range(1, 10) if v not in used]
def solve_mrv(board):
best = None
for r in range(9):
for c in range(9):
if board[r][c] == 0:
opts = candidates(board, r, c)
if not opts:
return False # forward check: some cell has no legal digit
if best is None or len(opts) < len(best[2]):
best = (r, c, opts)
if best is None:
return True # no empty cells remain
r, c, opts = best
for v in opts:
board[r][c] = v
if solve_mrv(board):
return True
board[r][c] = 0
return False
rows = ["530070000", "600195000", "098000060",
"800060003", "400803001", "700020006",
"060000280", "000419005", "000080079"]
puzzle = [[int(ch) for ch in row] for row in rows]
print(solve_mrv(puzzle)) # True
print(puzzle[0]) # [5, 3, 4, 6, 7, 8, 9, 1, 2]The template is still choose, explore, unchoose. The only changes are how the next cell is selected and the early return False when a domain is empty.
Common Errors
- Forgetting to restore incrementally maintained domains on unchoose. This corrupts later branches without any error message.
- Expecting value ordering to help when you enumerate all solutions. Every value gets tried anyway, so only variable ordering and pruning shrink the tree.
- Treating MRV ties as unimportant. A common tie-breaker is the degree heuristic: pick the cell that constrains the most other empty cells.
Exercise
You change solve_mrv to count all solutions instead of stopping at the first. Which of MRV, least constraining value, and forward checking still reduce the number of nodes visited, and why?
Show answer
MRV and forward checking still help. MRV changes the shape of the tree so dead ends show up near the root, and forward checking cuts branches whose domains are empty. Least constraining value only changes which branch is explored first. When you count every solution, every branch is explored, so the total work stays the same.
Exercise
In solve_mrv, what happens if a cell has exactly one candidate, and why is it good that MRV picks it first?
Show answer
MRV picks it, since 1 is the smallest possible domain, and the loop tries that single digit without branching. Filling forced cells first shrinks the neighbors' domains early, which exposes contradictions sooner and costs no extra branching.