Sub topic 14
Ordering Heuristics and Forward Checking
This chapter assumes you have read the Sudoku and N-Queens chapters. You should be comfortable with the choose-explore-unchoose template, restoring state after a recursive call, and Python sets and dictionaries.
The Sudoku solver from the earlier chapter always filled the first empty cell in reading order and tried the digits 1 through 9 in order. Both of those decisions were arbitrary. Every complete search visits the same set of solutions, but the order of choices decides how large the tree is before you reach one. This chapter covers three changes that shrink the tree in practice:
- Variable ordering decides which unfilled position to work on next.
- Value ordering decides which candidate to try first at that position.
- Forward checking detects a dead end one step earlier by tracking what each unfilled position can still hold.
The vocabulary of constraint problems
A constraint satisfaction problem has three parts. Variables are the positions you must fill, such as Sudoku cells. Each variable has a domain, the set of values it may still take, such as the digits 1 to 9. Constraints are the rules that link variables, such as "no two cells in a row share a digit." Two variables that share a constraint are peers. In Sudoku, every cell has 20 peers: 8 in its row, 8 in its column, and 4 more in its box.
In this vocabulary, one level of the state-space tree is "assign a value to one variable." The heuristics below change which variable each level uses and the order of the branches under it.
Variable ordering: fail first
The minimum remaining values (MRV) heuristic picks the unfilled variable with the smallest domain. People also call it the "fail-first" principle. If some cell has only one legal digit, place it now. If some cell has zero legal digits, the current partial solution is already dead, and MRV finds that out at once.
Look at the branching factor to see why this helps. If you choose a cell with 6 candidates, the node has 6 children, and most of them may fail deep in the tree. A cell with 2 candidates gives 2 children. Picking narrow cells first keeps the top of the tree thin, and the top of the tree is where every extra branch gets multiplied by everything below it.
Value ordering: succeed first
After you pick a variable, the least constraining value (LCV) heuristic tries first the value that removes the fewest options from the peers' domains. It leaves the most room for the rest of the puzzle, so the first branch is the one most likely to lead to a solution.
The two heuristics pull in opposite directions on purpose. Variable ordering aims to fail fast, because every variable has to be assigned eventually and you want to discover early that the current state is hopeless. Value ordering aims to succeed fast, because you only need one value to work.
Forward checking
Plain backtracking checks a constraint only when it tries to place a value. Forward checking does more work at placement time. After assigning a value to a variable, it removes that value from the domain of every unassigned peer. If any peer's domain becomes empty (a domain wipeout), the assignment fails right away, without recursing.
Without forward checking, the solver might place several more digits before it reaches the cell that has no options left. With forward checking, it rejects the bad digit at the moment it is placed.
Forward checking changes shared state, so it needs careful undo, just like path.pop() did in earlier chapters. Every value removed from a peer's domain must be put back when the branch fails.
A Sudoku solver with MRV, LCV, and forward checking
The program below has two solvers. The first is the baseline from the Sudoku chapter, with a node counter added. The second keeps a domain for every empty cell and applies all three techniques. Both count how many times their recursive function is called, so you can compare the sizes of the two trees.
PUZZLE = [
"53..7....",
"6..195...",
".98....6.",
"8...6...3",
"4..8.3..1",
"7...2...6",
".6....28.",
"...419..5",
"....8..79",
]
def parse(rows):
return [[0 if ch == '.' else int(ch) for ch in row] for row in rows]
def peers_of(r, c):
br, bc = 3 * (r // 3), 3 * (c // 3)
ps = {(r, j) for j in range(9)} | {(i, c) for i in range(9)}
ps |= {(i, j) for i in range(br, br + 3) for j in range(bc, bc + 3)}
ps.discard((r, c))
return ps
PEERS = {(r, c): peers_of(r, c) for r in range(9) for c in range(9)}
def legal_values(board, r, c):
used = {board[pr][pc] for pr, pc in PEERS[(r, c)]}
return {v for v in range(1, 10) if v not in used}
# Baseline: first empty cell, digits 1..9, no forward checking.
def solve_plain(board, stats):
stats['nodes'] += 1
for r in range(9):
for c in range(9):
if board[r][c] == 0:
for v in range(1, 10):
if v in legal_values(board, r, c):
board[r][c] = v
if solve_plain(board, stats):
return True
board[r][c] = 0
return False
return True
# MRV + LCV + forward checking.
def solve_smart(board, stats):
domains = {(r, c): legal_values(board, r, c)
for r in range(9) for c in range(9) if board[r][c] == 0}
def backtrack():
stats['nodes'] += 1
if not domains:
return True
cell = min(domains, key=lambda k: len(domains[k])) # MRV
r, c = cell
domain = domains.pop(cell)
# LCV: try values that appear in the fewest peer domains first.
order = sorted(domain, key=lambda v: sum(
1 for p in PEERS[cell] if p in domains and v in domains[p]))
for v in order:
board[r][c] = v
removed = []
wiped_out = False
for p in PEERS[cell]: # forward check
if p in domains and v in domains[p]:
domains[p].remove(v)
removed.append(p)
if not domains[p]:
wiped_out = True
break
if not wiped_out and backtrack():
return True
for p in removed: # undo pruning
domains[p].add(v)
board[r][c] = 0
domains[cell] = domain # undo the pop
return False
return backtrack()
for name, solver in (("plain", solve_plain), ("smart", solve_smart)):
board = parse(PUZZLE)
stats = {'nodes': 0}
ok = solver(board, stats)
print(f"{name}: solved={ok}, nodes={stats['nodes']}")
for row in board:
print(''.join(map(str, row)))When you run it, both solvers print the same completed grid, which starts with the row 534678912. The node counts differ a lot. On this easy puzzle, MRV with forward checking hardly branches at all, because almost every cell it picks has exactly one candidate. On harder puzzles the gap grows to several orders of magnitude.
Details worth checking
domains.pop(cell)removes the chosen cell before recursing. The solver therefore never treats an assigned cell as unassigned. On failure,domains[cell] = domainputs back the same set object, which by that point holds exactly its original values again.- The undo loop runs on every path that does not succeed, including the wipeout path. The
removedlist records each peer that was changed, including the peer that was wiped out, so the restore is exact. - If the starting puzzle already has a cell with an empty domain, MRV picks that cell first. Its loop runs zero times, and the solver returns
Falseimmediately. - After a successful solve,
domainsis left empty and is not restored. That is fine because the function returns and nothing reads it again.
Costs and trade-offs
Each technique adds work at every node to reduce the number of nodes.
| Technique | Extra work per node | What it buys | When it is not worth it |
|---|---|---|---|
| MRV | Scan all unassigned domains, O(V) | Thin upper tree, early detection of dead states | Problems where all domains stay the same size |
| LCV | Count peer conflicts for each value | First solution found sooner | Enumerating all solutions |
| Forward checking | Update every peer, plus undo | Cuts a branch one level earlier | Loosely constrained problems with few wipeouts |
None of these changes the worst-case exponential bound from the complexity chapter. They change the typical case. Measure with a node counter, as the program above does, rather than guessing.
Common errors
- Forgetting to restore domains. The solver then quietly discards valid values in sibling branches and reports "no solution" for solvable inputs.
- Restoring values that were never removed. If you add
vback to every peer instead of only the peers inremoved, a peer can gain a value that an earlier assignment had ruled out. - Recomputing domains from scratch at every node. This is correct, but it throws away the bookkeeping that makes forward checking cheap.
- Treating forward checking as full consistency. Forward checking looks only at the direct peers of the variable just assigned. It cannot see that two unassigned peers are each left with the same single value. Stronger methods such as arc consistency (AC-3) catch that case, but they cost more per node.
Beyond Sudoku
The same ideas apply to N-Queens. If you treat each row as a variable whose domain is the set of safe columns, MRV picks the row with the fewest safe columns, and forward checking removes the attacked columns from every later row. Graph coloring, timetabling, and crossword filling follow the same pattern: keep domains for the variables, choose the narrowest one, and prune the peers.
Exercise
In solve_smart, suppose you delete the line domains[cell] = domain that runs before return False. Describe what goes wrong and give a situation where the solver gives a wrong answer.
Show answer
The cell stays removed from domains after its branch fails. The caller's loop then tries another value for an earlier cell, but the failed cell is no longer treated as unassigned, so it is never filled again and still holds 0 on the board. The search can reach not domains and return True with an empty cell left, reporting a "solution" that is incomplete. This happens on any puzzle that needs at least one real backtrack, where a cell's whole domain fails and an earlier choice has to change.
Exercise
You change the program to count all solutions of a puzzle that has many of them. Which of MRV, LCV, and forward checking should you keep, and why?
Show answer
Keep MRV and forward checking, because both remove subtrees that contain no solutions, and that saves work even in a full enumeration. Drop LCV. When every value must be tried anyway, the order of the values does not change the total work, so the per-node conflict counting is pure overhead.
Exercise
Forward checking accepts an assignment that leaves two unassigned cells in the same row, each with the domain {4}. Why doesn't forward checking reject it, and when will the solver find the conflict?
Show answer
Forward checking only checks that no peer of the just-assigned cell has an empty domain. Both cells still have one value, so the check passes. MRV will pick one of them next, because its domain size is 1, and assign 4. Forward checking then removes 4 from the other cell, wipes out its domain, and the branch fails one level later. Arc consistency would have found the conflict before that.