Constraint-Based Backtracking
Many puzzles, Sudoku and N-Queens among them, can be stated as variables that each need a value under rules that link them. Backtracking solves any such problem, and three additions make it far faster: keep a list of the values still possible for each variable, cross values off as soon as a neighbour takes them, and always work next on the variable with the fewest values left.
Variables, Domains and Constraints
A constraint satisfaction problem (CSP) has three parts. Variables are the things to decide. Each variable has a domain, the values it is allowed to take. Constraints are rules on groups of variables that say which combinations are allowed. A solution gives every variable a value from its domain with no rule broken.
Stating a puzzle this way pays off because one solver then handles all of them. In Sudoku the variables are the empty cells, the domains are the digits, and the constraints say no row, column or box repeats a digit. In N-Queens the variables are the rows, the domain is the column for that row's queen, and the constraints forbid shared columns and diagonals. Map colouring, exam timetabling and seating plans have the same shape.
Most CSP rules are binary: they link two variables, like "these two cells must differ". Binary rules can be drawn as a constraint graph, one node per variable and one line per rule. The neighbours of a variable in that graph are exactly the variables a new value can affect.
- Variables: what must be decided
- Domains: the values each variable may take
- Constraints: which combinations are allowed
- Solution: every variable set, no constraint broken
Backtracking Search on a CSP
- If every variable has a value, return the solution
- Pick an unassigned variable
- For each value in its domain that agrees with the variables already set: assign it
- Recurse; if the recursion succeeds, stop
- Otherwise remove the value and try the next one
- If no value works, return failure so the caller tries its next value
This is the usual backtracking template with the CSP parts plugged in: the path is the set of assignments so far, the options are a variable's domain, and the rule check is "no constraint with an assigned neighbour is broken".
Its weakness is that it only looks backwards. A value is checked against variables already set, never against the ones still waiting. A choice can quietly leave some later variable with no legal value, and the search will not notice until it reaches that variable, perhaps many levels deeper, after doing a lot of work that was doomed from the start.
On the 4×4 Sudoku in the tracer, plain backtracking in reading order puts 1 in the top-left cell, which is wrong, and makes 75 tries before it comes back to change it. It needs 101 tries in all.
- Same template: assign, recurse, unassign
- Checks only against assigned variables
- A bad early choice can survive for many levels
Forward Checking
Forward checking looks one step ahead. After assigning a value to a variable, remove that value from the domain of every unassigned neighbour that would clash with it. If any neighbour's domain becomes empty, that neighbour can never be filled, so undo the assignment at once and try the next value.
In the tracer, guessing 1 for the top-left cell leaves its row neighbour with only 2; placing that 2 strikes 2 from the next cell, whose domain becomes empty. The dead end is found two assignments after the guess, not 75 tries later. The whole puzzle takes 13 assignments and one undo.
Undo must restore exactly what was struck. Keep a list of the (variable, value) pairs removed by each assignment and put them back when it is undone, in the same way the basic template pops what it pushed.
The domains also make the rule check free. Every value still in a domain is consistent with all assigned neighbours, so the loop never needs to look at them again.
- After each assignment, strike the value from unassigned neighbours
- An empty domain means this branch cannot succeed: undo now
- Record what was struck so the undo can restore it
- Values left in a domain are already known to be consistent
Terms, operations, and practical uses
Key terms
- DomainThe values a variable may still take; it shrinks as neighbours are assigned.
- Wipe-outA domain that has become empty; the current branch cannot succeed.
- Fail-firstChoose the variable most likely to fail, so dead ends show up early.
- AC-3The queue-based procedure that makes every binary constraint arc consistent.
Related lessons and problems
- Backtracking FoundationsThe template this lesson builds on.
- Backtracking AlgorithmsState space trees, pruning and N-Queens.
- Graph ColoringColouring a constraint graph, with DSATUR.
- Sudoku Solver (problem)A full 9×9 CSP.
Code in Python, C++ and Java
PUZZLE = [0, 0, 0, 3,
0, 0, 0, 0,
2, 0, 3, 1,
0, 0, 0, 2]
def peers(i):
r, c = divmod(i, 4)
return [j for j in range(16) if j != i and
(j // 4 == r or j % 4 == c or (j // 8, j % 4 // 2) == (i // 8, c // 2))]
PEERS = [peers(i) for i in range(16)]
def solve_csp(grid):
grid = grid[:]
domains = [{grid[i]} if grid[i] else {1, 2, 3, 4} for i in range(16)]
for i in range(16):
if grid[i]:
for j in PEERS[i]:
if not grid[j]:
domains[j].discard(grid[i])
stats = {"assignments": 0, "dead ends": 0}
def search():
empty = [i for i in range(16) if not grid[i]]
if not empty:
return True
cell = min(empty, key=lambda i: len(domains[i]))
for value in sorted(domains[cell]):
stats["assignments"] += 1
grid[cell] = value
pruned = [j for j in PEERS[cell] if not grid[j] and value in domains[j]]
for j in pruned:
domains[j].discard(value)
if all(domains[j] for j in pruned) and search():
return True
if not all(domains[j] for j in pruned):
stats["dead ends"] += 1
for j in pruned:
domains[j].add(value)
grid[cell] = 0
return False
if any(not domains[i] for i in range(16)):
return None, stats
return (grid if search() else None), stats
def solve_plain(grid):
grid, tries = grid[:], 0
def search():
nonlocal tries
if 0 not in grid:
return True
cell = grid.index(0)
for value in range(1, 5):
tries += 1
if all(grid[j] != value for j in PEERS[cell]):
grid[cell] = value
if search():
return True
grid[cell] = 0
return False
search()
return tries
solution, stats = solve_csp(PUZZLE)
for r in range(4):
print(*solution[r * 4:r * 4 + 4])
print("forward checking + MRV:", stats["assignments"], "assignments,", stats["dead ends"], "dead end")
print("plain backtracking:", solve_plain(PUZZLE), "value tries")
broken = PUZZLE[:]
broken[5] = 4
result, stats = solve_csp(broken)
print("with a 4 added at row 2, column 2:", "solved" if result else "no solution", "after", stats["assignments"], "assignments")#include <iostream>
#include <set>
#include <vector>
using namespace std;
vector<int> PEERS[16];
vector<int> grid;
set<int> domains[16];
int assignments, deadEnds, tries;
bool search() {
int cell = -1;
for (int i = 0; i < 16; i++)
if (!grid[i] && (cell < 0 || domains[i].size() < domains[cell].size())) cell = i;
if (cell < 0) return true;
vector<int> values(domains[cell].begin(), domains[cell].end());
for (int value : values) {
assignments++;
grid[cell] = value;
vector<int> pruned;
for (int j : PEERS[cell])
if (!grid[j] && domains[j].count(value)) pruned.push_back(j);
bool wipeout = false;
for (int j : pruned) {
domains[j].erase(value);
if (domains[j].empty()) wipeout = true;
}
if (!wipeout && search()) return true;
if (wipeout) deadEnds++;
for (int j : pruned) domains[j].insert(value);
grid[cell] = 0;
}
return false;
}
bool solveCsp(vector<int> start) {
grid = start; assignments = deadEnds = 0;
for (int i = 0; i < 16; i++) {
domains[i].clear();
if (grid[i]) domains[i].insert(grid[i]);
else domains[i] = {1, 2, 3, 4};
}
for (int i = 0; i < 16; i++)
if (grid[i])
for (int j : PEERS[i])
if (!grid[j]) domains[j].erase(grid[i]);
for (int i = 0; i < 16; i++)
if (domains[i].empty()) return false;
return search();
}
bool plain() {
int cell = -1;
for (int i = 0; i < 16 && cell < 0; i++)
if (!grid[i]) cell = i;
if (cell < 0) return true;
for (int value = 1; value <= 4; value++) {
tries++;
bool ok = true;
for (int j : PEERS[cell]) if (grid[j] == value) ok = false;
if (ok) {
grid[cell] = value;
if (plain()) return true;
grid[cell] = 0;
}
}
return false;
}
int main() {
for (int i = 0; i < 16; i++)
for (int j = 0; j < 16; j++)
if (j != i && (j / 4 == i / 4 || j % 4 == i % 4 || (j / 8 == i / 8 && j % 4 / 2 == i % 4 / 2)))
PEERS[i].push_back(j);
vector<int> puzzle = {0, 0, 0, 3,
0, 0, 0, 0,
2, 0, 3, 1,
0, 0, 0, 2};
solveCsp(puzzle);
for (int r = 0; r < 4; r++)
cout << grid[r * 4] << " " << grid[r * 4 + 1] << " " << grid[r * 4 + 2] << " " << grid[r * 4 + 3] << "\n";
cout << "forward checking + MRV: " << assignments << " assignments, " << deadEnds << " dead end\n";
grid = puzzle; tries = 0; plain();
cout << "plain backtracking: " << tries << " value tries\n";
vector<int> broken = puzzle;
broken[5] = 4;
bool ok = solveCsp(broken);
cout << "with a 4 added at row 2, column 2: " << (ok ? "solved" : "no solution") << " after " << assignments << " assignments\n";
}import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
public class Main {
static List<List<Integer>> peers = new ArrayList<>();
static int[] grid;
static List<TreeSet<Integer>> domains = new ArrayList<>();
static int assignments, deadEnds, tries;
static boolean search() {
int cell = -1;
for (int i = 0; i < 16; i++)
if (grid[i] == 0 && (cell < 0 || domains.get(i).size() < domains.get(cell).size())) cell = i;
if (cell < 0) return true;
for (int value : new ArrayList<>(domains.get(cell))) {
assignments++;
grid[cell] = value;
List<Integer> pruned = new ArrayList<>();
for (int j : peers.get(cell))
if (grid[j] == 0 && domains.get(j).contains(value)) pruned.add(j);
boolean wipeout = false;
for (int j : pruned) {
domains.get(j).remove(value);
if (domains.get(j).isEmpty()) wipeout = true;
}
if (!wipeout && search()) return true;
if (wipeout) deadEnds++;
for (int j : pruned) domains.get(j).add(value);
grid[cell] = 0;
}
return false;
}
static boolean solveCsp(int[] start) {
grid = start.clone();
assignments = deadEnds = 0;
domains.clear();
for (int i = 0; i < 16; i++) {
TreeSet<Integer> d = new TreeSet<>();
if (grid[i] != 0) d.add(grid[i]);
else for (int v = 1; v <= 4; v++) d.add(v);
domains.add(d);
}
for (int i = 0; i < 16; i++)
if (grid[i] != 0)
for (int j : peers.get(i))
if (grid[j] == 0) domains.get(j).remove(grid[i]);
for (TreeSet<Integer> d : domains)
if (d.isEmpty()) return false;
return search();
}
static boolean plain() {
int cell = -1;
for (int i = 0; i < 16 && cell < 0; i++)
if (grid[i] == 0) cell = i;
if (cell < 0) return true;
for (int value = 1; value <= 4; value++) {
tries++;
boolean ok = true;
for (int j : peers.get(cell)) if (grid[j] == value) ok = false;
if (ok) {
grid[cell] = value;
if (plain()) return true;
grid[cell] = 0;
}
}
return false;
}
public static void main(String[] args) {
for (int i = 0; i < 16; i++) {
List<Integer> p = new ArrayList<>();
for (int j = 0; j < 16; j++)
if (j != i && (j / 4 == i / 4 || j % 4 == i % 4 || (j / 8 == i / 8 && j % 4 / 2 == i % 4 / 2)))
p.add(j);
peers.add(p);
}
int[] puzzle = {0, 0, 0, 3,
0, 0, 0, 0,
2, 0, 3, 1,
0, 0, 0, 2};
solveCsp(puzzle);
for (int r = 0; r < 4; r++)
System.out.println(grid[r * 4] + " " + grid[r * 4 + 1] + " " + grid[r * 4 + 2] + " " + grid[r * 4 + 3]);
System.out.println("forward checking + MRV: " + assignments + " assignments, " + deadEnds + " dead end");
grid = puzzle.clone();
tries = 0;
plain();
System.out.println("plain backtracking: " + tries + " value tries");
int[] broken = puzzle.clone();
broken[5] = 4;
boolean ok = solveCsp(broken);
System.out.println("with a 4 added at row 2, column 2: " + (ok ? "solved" : "no solution") + " after " + assignments + " assignments");
}
}Step through it
Running on 4×4 grid: _ _ _ 3 / _ _ _ _ / 2 _ 3 1 / _ _ _ 2
Which Variable Next, Which Value First
Plain backtracking takes the variables in a fixed order. A CSP solver chooses the next variable as it goes, and the choice changes the size of the search enormously.
Minimum remaining values (MRV) picks the unassigned variable with the smallest domain. A variable with one value left costs no guessing at all, and one with zero values exposes a dead end immediately. This is the fail-first idea: if the branch is going to fail, find out with as little work as possible. In the tracer, MRV fills three forced cells before making any guess. A common tie-break is the degree heuristic: among equal domains, take the variable involved in the most constraints with unassigned variables.
The value order matters too, in the opposite direction. The least constraining value heuristic tries first the value that removes the fewest options from neighbouring domains. Variables should be chosen to fail fast, values to succeed fast: if a solution exists below this variable, the value that leaves neighbours the most room is most likely to reach it. When all solutions are wanted, value order makes no difference, since every value is tried anyway.
The same fewest-options-first idea shows up in graph coloring, where DSATUR colours next the vertex whose neighbours already use the most colours.
- MRV: smallest domain next, so dead ends appear early
- Degree heuristic: break MRV ties by most constraints with unassigned variables
- Least constraining value: try the value that leaves neighbours most choice
- Choose variables to fail fast, values to succeed fast
Stronger Checking: Arc Consistency
Forward checking only compares the new value with its neighbours. It misses clashes between two unassigned variables. In the tracer, after the wrong guess, two cells in the same row both have only {2} left. Both cannot have it, but forward checking does not compare them, so it needs one more assignment to see the problem.
Arc consistency closes that gap. For every constraint between two unassigned variables X and Y, remove from X's domain any value that has no compatible value left in Y's domain, and repeat until nothing changes. The usual procedure, AC-3, keeps a queue of variable pairs and re-checks a pair whenever one side's domain shrinks. Running it after every assignment is called maintaining arc consistency (MAC).
Stronger checking costs more per node but visits fewer nodes. On hard puzzles MAC usually wins; on easy ones forward checking is often enough. The "only one place for this digit" deductions people use for Sudoku are this kind of propagation done by hand.
- Forward checking: new value vs its neighbours only
- Arc consistency: every pair of linked unassigned variables
- AC-3: re-check a pair whenever one side's domain shrinks
- More work per node, fewer nodes
Cost, Limits and Practice
With n variables and domains of size d, the search can still try up to dⁿ combinations; general CSPs are NP-complete, so no heuristic removes the exponential worst case. What forward checking and MRV change is the typical case, often by orders of magnitude. Space is O(n · d) for the domains plus the undo lists.
An empty domain before the search even starts is an answer too: the problem has no solution, found with zero guesses. The last tracer step shows one, after a single extra given.
To practise, write a CSP solver for Sudoku Solver with per-cell candidate sets and MRV, then apply the same idea to N-Queens and the M-Coloring Problem. The backtracking lesson covers the state space tree these searches walk.
- Worst case stays dⁿ; heuristics change the typical case
- Space O(n · d) for domains and undo lists
- An empty domain at the start proves there is no solution