Module contents
Lesson 9 of 23Core 100 min

Constraint satisfaction: modeling, propagation and backtracking

CSPs open the black box of state: variables, domains and constraints enable general heuristics and inference propagation. This lesson studies modeling, backtracking with ordering heuristics, forward checking and arc consistency with AC-3, and builds a generic solver for hard sudokus and large n-queens problems.

After this lesson you can

  • Model real problems as CSPs by choosing variables, domains and constraints that propagate well.
  • Implement backtracking with MRV, degree and LCV and measure their effects through ablations.
  • Prove termination, uniqueness of the result and complexity of AC-3.
  • Integrate forward checking and MAC into backtracking and compare their pruning.
  • Distinguish arc, path and global consistency and recognize when propagation suffices.

Before you start

Motivation: opening the black box of state

In previous lessons the state was a black box. Uninformed search and A* could ask only three things: which actions exist, what states they lead to, and whether a state is a goal. To solve sudoku this way, the state is a partially filled grid, actions are “write digit vv in cell cc,” and the goal is “a full, correct grid.” Search does not know an empty cell in row 3 cannot be 7 because that row already contains 7: it discovers this, if at all, when it reaches a leaf and the test fails.

Many real problems have much richer structure. An exam timetable has several variables (each exam’s slot), a few possible values, and rules about pairs or groups of variables (exams sharing students cannot coincide; each slot has limited seats). The same applies to map coloring, radio-frequency allocation, product configuration, shift scheduling, chip component placement and sudoku.

If the algorithm sees that structure it can do two things opaque search cannot:

  • Use general, domain-independent heuristics: “assign the variable with fewest options first” works for sudoku and timetabling alike.
  • Infer without searching. An assignment removes values from other variables, which removes others, and sometimes the entire problem is solved (or proved impossible) without trying anything. This is constraint propagation.

This lesson builds constraint programming’s two basic tools: backtracking with good heuristics and propagation by arc consistency, separately and together. At the end you will have a generic solver that solves Inkala’s sudoku and 100 queens in the browser, know how to measure each piece’s contribution, and understand the internals of an industrial solver such as CP-SAT. The next lesson, structure and constraint programming, exploits the constraint graph’s shape and global constraints.

What is a CSP?

The relation is a subset of a Cartesian product, that is, a relation in the set-theoretic sense. In practice it is rarely stored as a table: it is a function deciding whether a tuple is allowed (X1≠X2X_1 \neq X_2, X1+X2≤10X_1 + X_2 \le 10) or a specialized algorithm. The space of complete assignments has ∏i∣Di∣\prod_i \abs{D_i} elements, dnd^n if all domains have size dd; a sudoku with 60 empty cells has 960≈1.8×10579^{60} \approx 1.8\times 10^{57}.

Five models

Australia coloring. Russell and Norvig’s textbook example. Variables: the seven states and territories, {WA,NT,SA,Q,NSW,V,T}\{WA, NT, SA, Q, NSW, V, T\}. Domains: {rojo,verde,azul}\{\text{rojo}, \text{verde}, \text{azul}\}. Constraints: regions sharing a border have different colors, nine in total (WA≠NTWA \neq NT, WA≠SAWA \neq SA, NT≠SANT \neq SA, NT≠QNT \neq Q, SA≠QSA \neq Q, SA≠NSWSA \neq NSW, SA≠VSA \neq V, Q≠NSWQ \neq NSW, NSW≠VNSW \neq V). Tasmania touches none. This is graph coloring.

Sudoku. 81 variables, one per cell. Domain {1,…,9}\{1, \dots, 9\}, or the clue’s value for a given cell (a unary constraint). Constraints: the nine cells in each row, column and box are distinct. These can be written as 27 constraints of arity 9 or binary constraints Xp≠XqX_p \neq X_q for each pair sharing a unit; an exercise asks how many.

nn queens. Place nn queens on an n×nn\times n board without attacks. The good model does not use one variable per square: it uses variable QjQ_j per column, whose value is that column’s queen’s row. “One queen per column” is satisfied by construction and only (n2)\binom{n}{2} binary constraints remain, Qi≠QjQ_i \neq Q_j and ∣Qi−Qj∣≠∣i−j∣\abs{Q_i - Q_j} \neq \abs{i - j}.

Cryptarithmetic. In SEND+MORE=MONEY\text{SEND} + \text{MORE} = \text{MONEY} each letter is a distinct digit and leading digits are not 0. A naive model uses the eight letters and one enormous constraint, 1000S+100E+10N+D+1000M+100O+10R+E=10000M+1000O+100N+10E+Y1000S + 100E + 10N + D + 1000M + 100O + 10R + E = 10000M + 1000O + 100N + 10E + Y. A model that propagates better adds carries c1,…,c4∈{0,1}c_1, \dots, c_4 \in \{0, 1\} and writes one equation per column, as in addition by hand:

D+E=Y+10c1,N+R+c1=E+10c2,E+O+c2=N+10c3,S+M+c3=O+10c4,c4=M.D + E = Y + 10c_1,\quad N + R + c_1 = E + 10c_2,\quad E + O + c_2 = N + 10c_3,\quad S + M + c_3 = O + 10c_4,\quad c_4 = M.

Each equation touches at most five variables and the solver can reason with it once only a few are fixed: the last immediately forces M=1M = 1 because M≠0M \neq 0 and a carry is at most 1. The unique solution is 9567+1085=106529567 + 1085 = 10652.

Exam timetables. One variable TeT_e per exam, with available slots as its domain. Two exams sharing a student cannot coincide: Te≠TfT_e \neq T_f, graph coloring again. Each slot tt holds at most PP students: ∑ene 1[Te=t]≤P\sum_e n_e\,\ind[T_e = t] \le P, where nen_e is enrollment. This last constraint is not binary; it depends on all exams at once and you will solve it at the lesson’s end using a professional solver.

What is hard and what is easy

Deciding whether a finite-domain CSP has a solution is NP-complete. It is in NP because a solution can be verified in polynomial time (if relations can be evaluated in polynomial time), and NP-hard because 3-coloring graphs is a special case: each vertex is a variable with a domain of size 3 and each edge an ≠\neq constraint. This is one of the most direct polynomial reductions. Thus do not expect an efficient worst-case algorithm. This lesson aims for something else: solving typical cases (and many genuinely hard cases) while exploring a tiny fraction of the space.

Constraints and their graph

Constraints are classified by arity, and each class requires different treatment.

  • Unary (k=1k = 1): restrict one variable, such as sudoku clues or “Physics cannot be on Monday.” Remove them beforehand by removing domain values that fail them; the network is then node-consistent.
  • Binary (k=2k = 2): the focus of this lesson. Almost all classical propagation theory (arc and path consistency) was formulated for binary networks.
  • Higher-arity or global: “these nine cells are all different” (AllDifferent\text{AllDifferent}), “the sum of exam sizes in each slot does not exceed capacity” (a linear constraint), “these tasks do not overlap in time.” They are called global when they have an arbitrary number of variables and a dedicated filtering algorithm. The next lesson studies them as global constraints and their filtering.

The graph is not decorative: its shape determines difficulty. If it is a tree, the CSP is solved in O(nd2)\bigO(nd^2) time; if it has independent components (like Tasmania), solve them separately and costs add instead of multiply; if a small variable set cuts all cycles, try its values and solve trees. This is the theory of tree-structured CSPs in the next lesson. Here we use it differently: propagation algorithms send information along edges.

Every finite CSP can be binarized

Any finite-arity constraint can be rewritten using binary constraints and added variables. There are two classical constructions; see both on C1C_1: X+Y=ZX + Y = Z with X,Y,Z∈{1,2,3}X, Y, Z \in \{1, 2, 3\}, whose allowed relation is R1={(1,1,2),(1,2,3),(2,1,3)}R_1 = \{(1, 1, 2), (1, 2, 3), (2, 1, 3)\}.

  • Hidden variable. Add variable H1H_1 whose domain is the three tuples of R1R_1, and three binary constraints saying “XX is H1H_1‘s first component,” “YY the second,” and “ZZ the third.” Original variables are retained.
  • Dual graph. Each constraint becomes a variable whose domain is its relation; two dual variables sharing original variables receive a binary constraint requiring their tuples to agree on them. If also C2C_2: Y<ZY < Z, C2C_2‘s dual variable has domain {(1,2),(1,3),(2,3)}\{(1, 2), (1, 3), (2, 3)\} and the constraint between both duals requires YY and ZZ to match in both tuples.

Both transformations preserve exactly the solutions (there is a bijection between original and binarized solutions), so binary theory in principle covers any finite CSP. Bacchus and van Beek (1998) compared backtracking with forward checking on both encodings and on the original problem, concluding that binarization is viable in some circumstances, not generally. A third, most tempting and most used way is decomposing the constraint into binary constraints over the same variables, such as “all different” into pairs ≠\neq. This adds no variables but loses propagation strength: each binary constraint sees two variables at once and cannot deduce what is visible only by looking at all nine in a row. Hidden variables lose nothing (arc consistency on them equals generalized arc consistency of the original constraint, defined with sudoku below), but their domain can be enormous: 9!=3628809! = 362880 tuples for a sudoku row. We return to this with numbers.

Backtracking: why commutativity removes factor n!n!

Formulate a CSP as a state-space search problem: the initial state is the empty assignment, an action assigns a value to an unassigned variable, and the goal is a complete consistent assignment. All solutions lie at depth exactly nn.

At depth ℓ\ell, n−ℓn - \ell variables remain free and each admits dd values, so the branching factor is (n−ℓ)d(n - \ell)d and the tree has

∏ℓ=0n−1(n−ℓ) d=n! dn\prod_{\ell = 0}^{n-1} (n - \ell)\,d = n!\,d^n

leaves, although only dnd^n distinct complete assignments exist. Each assignment appears n!n! times, once for each possible order of its nn choices. The remedy is that assignment commutes: {WA=rojo,NT=verde}\{WA = \text{rojo}, NT = \text{verde}\} is the same assignment in either order. Thus it suffices to choose one variable at each node and branch only over its values.

Proof

Induct on the number of free variables. With zero, the node is a leaf and its assignment is the unique complete extension of itself. If m>0m > 0 remain and the node chooses XX, every complete extension assigns XX exactly one value vv, thus extends exactly one child, that of X=vX = v; by induction it appears at exactly one leaf in that child’s subtree. Counting leaves counts complete assignments: ∏i∣Di∣\prod_i \abs{D_i}.

∎

The chosen variable may vary between nodes without losing completeness; the next section’s dynamic heuristics exploit this. The resulting algorithm is depth-first search checking constraints as soon as they can be checked.

def backtracking(asignacion):
    if asignacion es completa:
        return asignacion
    X = elegir_variable(asignacion)                 # una sola variable por nodo
    for v in ordenar_valores(X, asignacion):
        if v es consistente con asignacion:
            asignacion[X] = v
            if inferir(X, v):                       # opcional: propagar y fallar pronto
                resultado = backtracking(asignacion)
                if resultado is not None:
                    return resultado
            deshacer X y todo lo que haya inferido inferir
    return None                                      # ningún valor sirve: retroceder

Three gaps remain in that skeleton, and the rest of the lesson fills them: which variable to select, in what order to try values and what to infer after each assignment. Memory is O(n)\bigO(n) recursion levels plus what is needed to undo inferences; worst-case time is O(dn)\bigO(d^n) nodes.

Ordering heuristics: fail first, succeed first

Variable and value ordering heuristics choose the next variable and the order of its values. The three classics are:

  • MRV, minimum remaining values: choose the variable with fewest legal values, those compatible with the current assignment. If one has zero, choose it and the node fails immediately without branching.
  • Degree: among ties, choose the variable in the most constraints with still-free variables. It breaks MRV ties. The combination matches Brélaz’s (1979) DSATUR graph-coloring heuristic, choosing the vertex with most distinct colors among neighbors and breaking ties by degree.
  • LCV, least constraining value: order the chosen variable’s values by increasing number of values they would remove from free neighbors’ domains.

The first two follow the principle Haralick and Elliott (1980) called fail first: “to succeed, try first where you are most likely to fail.” LCV follows the opposite, succeed first. This is not a contradiction; understanding why is the section’s central point.

The variable. Every variable must eventually be assigned on every branch ending in a solution. If a variable will cause trouble, discover it near the root, when the discarded subtree is enormous, rather than deep down after exploring many combinations of the others that never had a future. A variable with one legal value is nearly free to assign (no branching) and propagates; one with zero prunes the entire branch. Choosing a variable changes the shape of the whole tree, whether looking for one solution, all solutions or proving there are none.

The value. For the selected variable, by contrast, only one value need be right. If the subtree has a solution, value order determines how quickly a good branch is entered; trying first the value leaving others most options maximizes the chance that branch has a solution. If looking for all solutions, or the subtree has none, all values will be traversed anyway and LCV saves nothing (it only costs checks to compute).

InteractiveMap coloring with heuristics
WANSWNTQVSAT search tree
node 16 of 16
  • blue
  • red
  • green
  • current path
  • backtracked branch (faded)
  • × inference empties a domain
Map
Inference
Colors
This configuration16 nodes, 9 backtracks
Without heuristics (same inference)16 nodes, 9 backtracks
MRV and degree7 nodes, 0 backtracks
Fixed variable orderWA, NSW, NT, Q, V, SA, T
Node 16: T = blue (depth 7).
Real backtracking on the Australia map and on a random map of Voronoi regions. Beside the map, the search tree: each dot is an assignment colored by its value; the current path is bold and undone branches faded. On Australia, fixed order WA, NSW, NT, Q, V, SA, T is chosen to trap simple backtracking: WA and NSW, which do not touch, receive the same color, NT and Q the other two, and SA has none left. Enable MRV and see which variable it selects second. Then switch to the random map (4 colors, randomly numbered regions) and compare the three readings for each inference; try other maps. With 3 colors the random map almost never has a solution, and the interesting question is the cost of proving it.

In Australia, with fixed order and no inference, backtracking needs 16 nodes and 9 backtracks (you will measure this in the lab). MRV eliminates all backtracks: after WA=azulWA = \text{azul} (the solver tries colors alphabetically), the variable with fewest legal values is a neighbor of WAWA, NTNT or SASA, with two colors each, not NSWNSW, which retains all three. MRV first “closes” the map’s core around SASA, exactly where the problem was.

The random map exaggerates this. Its regions are numbered randomly and fixed order follows numbers, jumping across the map: simple backtracking colors isolated regions that barely constrain one another and, when two leave a third colorless, backtracks chronologically through decisions unrelated to the conflict. This is thrashing. In the figure’s initial map (30 regions, 4 colors), it costs tens of thousands of nodes without heuristics and slightly under two hundred with forward checking; with MRV it colors without a single backtrack, because each selected region touches already colored ones.

Forward checking and its limit

MRV needs to know how many legal values remain for each variable. Recomputing this at each node costs checks; maintaining it is cheaper. This is the simplest form of inference.

With forward checking current domains are exactly the legal values, MRV reads directly from their sizes, and testing a value need not recheck consistency with assignments: the domain already guarantees it. Haralick and Elliott, who introduced it in the same paper as fail first, compared several look-ahead schemes on binary problems and found forward checking beat standard backtracking and the other methods on all cases tested, and Gaschnig’s backmarking on the largest problems.

Its limit is clear: it looks only at edges from the newly assigned variable. It does not reason between two unassigned variables. Assign WA=rojoWA = \text{rojo} and Q=verdeQ = \text{verde}. Forward checking leaves NT={azul}NT = \{\text{azul}\} (neighbor of both) and SA={azul}SA = \{\text{azul}\} (also neighbor of both). But NTNT and SASA are neighbors and cannot both be blue: the partial assignment is already doomed, but forward checking cannot see it because the edge between NTNT and SASA touches no assigned variable. It finds out one or two levels later, after futile branching.

Arc consistency and AC-3

The natural question is: what local inference would detect this? Look at the edge between NTNT and SASA alone. For NT=azulNT = \text{azul} to be possible, SASA needs some compatible value, and its only one, blue, is not compatible.

If a value a∈Dia \in D_i has no support in DjD_j, no solution can use it: any solution with Xi=aX_i = a would give XjX_j a value from DjD_j, none compatible. Removing it is safe. The operation removing unsupported values from an arc is revise(Xi,Xj)\text{revise}(X_i, X_j), and Mackworth (1977) organized it around a queue of pending arcs.

def AC3(csp):
    cola = todos los arcos (Xi, Xj), en los dos sentidos de cada restricción
    while cola no vacía:
        (Xi, Xj) = sacar(cola)
        if revise(Xi, Xj):                      # se ha borrado algún valor de Di
            if Di está vacío:
                return False                     # no hay solución
            for Xk in vecinos(Xi) - {Xj}:
                meter (Xk, Xi) en la cola si no está
    return True

def revise(Xi, Xj):
    borrado = False
    for a in Di:
        if no existe b en Dj con (a, b) en Rij:
            quitar a de Di;  borrado = True
    return borrado

Why reinsert (Xk,Xi)(X_k, X_i)? Because supports for XkX_k‘s values were in DiD_i, and DiD_i just shrank: a value of XkX_k may have lost support. Why not (Xj,Xi)(X_j, X_i)? This subtlety appears in the guided exercise. In Australia, after WA=rojoWA = \text{rojo} and Q=verdeQ = \text{verde} and forward checking, AC-3 revises (NT,SA)(NT, SA): NTNT‘s blue has no support, DNTD_{NT} becomes empty and the branch is pruned immediately.

InteractiveThe AC-3 queue
A ≠ CA ≠ BB ≠ DB < CA < DA123B123C123D123
Queue (10 arcs; select one to revise it)
  • remaining value
  • removed in the last revision
  • last revised arc (arrow points to XjX_j)
Revisions completed0
Values removed0 (remaining 12)
Arcs in queue10
FIFO · LIFO revisions16 · 10
Solutions (brute force)2
Choose an arc from the queue. Revising Xi→XjX_i \to X_j removes values of XiX_i that have no compatible value in XjX_j.
Constraint graph with domains drawn as tokens. The arc queue is below: click an arc to revise, or use ‘First’, ‘Last’ or ‘Empty (FIFO)’. Each revision crosses out unsupported tokens and highlights newly queued arcs pointing to the changed variable. Once the queue is empty, compare your revision count with FIFO and LIFO and check whether results agree. Try different orders on the four-variable network. Then switch to the two-color triangle: how many tokens does AC-3 remove? How many solutions are there? Enable the marker for values in no solution in the four-variable network and read the path-consistency reading.

What AC-3 guarantees

The figure suggests three facts: queue order changes work but not the result, the result never loses solutions, and it may retain values in no solution. The first two are theorems.

Proof

(1) As above, a value unsupported on an arc occurs in no solution, since a solution would give the other variable a domain value serving as support. Each AC-3 deletion removes an unsupported value relative to current domains, which contain each solution’s values (by induction over deletions).

(2) First, existence of a greatest subdomain. If D′D' and D′′D'' are arc-consistent, their componentwise union is too: a value of Di′∪Di′′D'_i \cup D''_i coming from Di′D'_i has support in Dj′⊆Dj′∪Dj′′D'_j \subseteq D'_j \cup D''_j, and likewise if it comes from Di′′D''_i. Since finitely many subdomains exist, the union of all arc-consistent ones contained in DD is arc-consistent and contains them all: it is D⋆D^\star. That AC-3 returns D⋆D^\star regardless of order is the final guided exercise: one invariant shows AC-3 never deletes a value of D⋆D^\star and another that the result is arc-consistent once the queue is empty.

(3) Arc (Xk,Xi)(X_k, X_i) enters the queue initially and thereafter only when DiD_i shrinks; the precise count is also in the exercises. Each entry causes a revision comparing each of at most dd values of DkD_k against at most dd of DiD_i: O(d2)\bigO(d^2) checks.

∎

Point (2) is a special case of a general fact: operations revise\text{revise} are monotone, contracting functions on the finite lattice of subdomains, and any “chaotic” iteration applying them until none changes anything converges to the same fixed point, the greatest one they all leave invariant. Apt (1999) formulated this for constraint propagation generally; it lets real solvers order the queue as convenient (e.g. cheap constraints first) without changing deductions.

Propagation in sudoku

Binarized sudoku is a perfect test bed: 81 variables, 810 ≠\neq constraints and propagation visible by eye. With ≠\neq constraints, revise(Xi,Xj)\text{revise}(X_i, X_j) deletes something only when DjD_j has a single value vv: then vv disappears from DiD_i. AC-3 on sudoku is thus the familiar naked single rule applied in a cascade: a decided cell removes its digit from its 20 neighbors, one is left with one candidate and removes again.

InteractiveSudoku propagation
812462456923471235712341356945791345679124591243612578124815894578914579145674563489134824581345612346952469238923687168924891246912369123682692389457289126924679246824679126826895689324569234572341234792372349359682346723468523672346939123792356792567237812367812368425723457
removal 286 of 286
  • clue
  • digit you added
  • determined by propagation
  • candidate removed in this step
  • cell causing removal (lost support)
Propagation
Candidates at this step275
At end: forward checking · AC-3 · GAC275 · 275 · 275
Determined cells21 of 81
Arc revisions1618 of 2592
Backtracks with MRV and forward checking10041
Backtracks with MRV and MAC3306
Backtracks with MRV, MAC and GAC97
Revision 1618, arc f9c9 → f9c7: f9c7 has only 4 left, so 4 in f9c9 has no support and is removed.
Each empty cell shows its candidates. Step through propagation: each deletion highlights the cell losing a candidate (red), the forcing cell (aqua) and the revised arc. Compare the three modes: forward checking from clues, AC-3 on binary constraints and GAC on the 27 ‘all different’ constraints. On Wikipedia's easy sudoku, AC-3 solves everything without search; on Escargot and Inkala, AC-3 removes no more candidates than forward checking. The last three readings show backtracks required by MRV backtracking using each propagation after each assignment. Click an empty cell and add a digit conflicting with another: which mode detects it before search?

The sudoku contrast is instructive. In Wikipedia’s, with 30 clues, forward checking leaves 183 candidates and AC-3, after 3953 arc revisions, leaves 81: one digit per cell, solved without branching. In AI Escargot (23 clues), which mathematician Arto Inkala presented in 2006 as the world’s hardest sudoku, and his 2012 puzzle with the same label (21 clues), AC-3 adds nothing to forward checking: 246 and 275 candidates, no empty cell with one candidate. Binary propagation runs out of ammunition at the root. Hard sudokus resist local deductions.

AC-4 and AC-2001 in a page

AC-3’s d3d^3 comes from each revision searching again from scratch for supports already found. Two classical ways avoid this, both reaching O(ed2)\bigO(ed^2), optimal in the general case: to establish that a value has no support under an arbitrary relation, inspect its dd possible partners, and there are 2ed2ed (value, arc) pairs. Mohr and Henderson (1986) proved this along with AC-4.

  • AC-4 (Mohr and Henderson, 1986) reasons value by value. For each arc (Xi,Xj)(X_i, X_j) and each a∈Dia \in D_i it stores a support counter in DjD_j, and for each b∈Djb \in D_j the list of values it supports. On deleting bb it traverses that list and decrements counters; a counter reaching 0 deletes its value. Time and memory O(ed2)\bigO(ed^2). The drawback is that initialization always costs Θ(ed2)\Theta(ed^2), even when nothing needs deleting, so in practice it often loses to AC-3.
  • AC-2001 (Bessière and Régin, 2001; the same idea appears as AC-3.1 in Zhang and Yap, 2001) retains AC-3’s arc queue and adds a pointer uˊltimo(Xi,a,Xj)\text{último}(X_i, a, X_j) to the last support found, with ordered domains. If that support remains alive, nothing is needed; otherwise search resumes from it, never from the beginning. Each (value, arc) pair traverses its partner domain at most once in the entire execution: time O(ed2)\bigO(ed^2) and memory O(ed)\bigO(ed). Bessière, Régin, Yap and Zhang (2005) proved worst-case optimality.

In practice something else matters: many constraints admit a specialized revise\text{revise} much cheaper than the generic one. For Xi≠XjX_i \neq X_j it suffices to check whether ∣Dj∣=1\abs{D_j} = 1; for Xi<XjX_i < X_j compare with max⁡Dj\max D_j. Real solvers use no table of checks: each constraint brings its own propagator.

Before search, AC-3 cleans what it can. During search we can go further.

The first round of that AC-3 call does exactly what forward checking does. Then it continues: if any DYD_Y changed, it queues arcs pointing to YY, and information travels as far through the graph as necessary.

Proof

Compare domains at a common node. By induction on depth, MAC domains are contained in forward-checking domains: they are equal at the root, and after assigning X=vX = v forward checking deletes neighbor values incompatible with vv, exactly those deleted by MAC’s (Y,X)(Y, X) revisions applied to already smaller domains; MAC may delete more. With smaller domains, a domain empty under forward checking is also empty under MAC, so wherever one fails the other does too, and values MAC tries at each node are a subset of the other’s. Since MAC never deletes a value in a solution, it preserves all solution leaves of the forward-checking tree in the same order: both find the same first solution, and MAC visits a subset of the nodes before it.

∎

With dynamic heuristics such as MRV this guarantee disappears: different domains lead solvers to select different variables, and trees are no longer comparable node by node. In practice MAC still explores far fewer nodes, as the lab shows, but that is an empirical fact, not a theorem.

More pruning does not automatically mean less time, because each MAC node costs more. For two decades conventional wisdom following Haralick and Elliott’s experiments held forward checking to be the sweet spot. Sabin and Freuder (1994) presented contrary evidence (“Contradicting conventional wisdom in constraint satisfaction”) and proposed reconsidering full arc consistency during search. Propagating to a fixed point at every node is now standard in constraint solvers.

The lab’s Inkala sudoku numbers with MRV show detail: forward checking needs 10122 nodes and 10041 backtracks; MAC needs 3387 nodes and 3306 backtracks, three times fewer. But MAC performs 1064630 constraint checks versus 231527, 4.6 times more, because each node triggers hundreds of arc revisions. With our generic revise, MAC takes longer than forward checking on that sudoku: AC-2001 and specialized propagators target precisely the per-node cost. With global constraints the reduction in backtracks is no longer a factor of 3: it is a factor of 34 relative to binary MAC, as you will see.

Beyond arcs: path consistency and kk-consistency

Arc consistency is local to each constraint. Its limit appears in the smallest example: three variables X,Y,ZX, Y, Z with domain {r,v}\{r, v\} and constraints X≠YX \neq Y, Y≠ZY \neq Z, X≠ZX \neq Z, a two-color triangle. Every value has support on every arc (rr in XX is supported by vv in YY, and so on), the network is arc-consistent and AC-3 removes nothing, but the triangle cannot be colored with two colors. Arc consistency does not detect every inconsistency.

1-consistency is node consistency; 2-consistency is arc consistency; and for binary networks, 3-consistency is path consistency. In the triangle, consistent assignment {X=r,Y=v}\{X = r, Y = v\} cannot be extended to ZZ: the network is not 3-consistent. A path-consistency algorithm removes that pair from the relation between XX and YY, and also {X=v,Y=r}\{X = v, Y = r\}; the relation becomes empty and the problem is declared unsolvable without search. This is shown by the queue figure’s “path consistency” reading.

How much consistency avoids search? Order variables X1,…,XnX_1, \dots, X_n; a variable’s width in that order is the number of earlier neighbors, the order’s width is the maximum, and the graph’s is the minimum over all orders.

Proof

Suppose X1,…,Xi−1X_1, \dots, X_{i-1} have a consistent assignment. XiX_i has j≤k−1j \le k - 1 neighbors among them. The assignment restricted to those jj neighbors is consistent (part of a consistent assignment), and by (j+1)(j + 1)-consistency, available because j+1≤kj + 1 \le k and consistency is strong, there is a value of XiX_i compatible with them all. XiX_i shares no constraints with the other earlier variables, so the extended assignment is consistent. If j=0j = 0, DiD_i need only be nonempty, which is 1-consistency.

∎

Two consequences. A network of nn variables that is strongly nn-consistent is solved without backtracking in any order. A tree has width 1 (order from the root: each node has one earlier neighbor, its parent), so arc consistency suffices on a tree for backtrack-free search. This underlies the linear tree-structured CSP algorithm in the next lesson.

Why not always impose kk-consistency with large kk? Because time and memory are exponential in kk (the (nk−1)dk−1\binom{n}{k-1}d^{k-1} assignments of k−1k - 1 variables must be traversed), and enforcing it can add constraints between formerly unconnected variables, increasing graph width and possibly requiring even greater consistency. General NP-completeness guarantees no polynomial-cost propagation always suffices. Practice keeps arc consistency (and its global-constraint version) inside MAC and leaves the rest to search.

Implementation from scratch

The lab builds a generic binary CSP solver: domains as sets, constraints as functions, AC-3, backtracking with MRV, degree, LCV, forward checking and MAC, and an all-different propagator. All in pure Python in the browser.

[ ]A binary CSP and the Australia mapBrowser
from itertools import combinations

class CSP:
    """CSP binario: dominios como conjuntos y restricciones como funciones ok(a, b)."""

    def __init__(self, variables, dominios):
        self.variables = list(variables)
        self.dominios = {X: set(dominios[X]) for X in self.variables}
        self.vecinos = {X: [] for X in self.variables}
        self.rel = {}                                  # (X, Y) -> función ok(a, b)

    def restringe(self, X, Y, ok):
        """Añade la restricción ok(valor de X, valor de Y); si ya había una entre X e Y, se conjugan."""
        if (X, Y) in self.rel:
            previa = self.rel[X, Y]
            ok = lambda a, b, p=previa, q=ok: p(a, b) and q(a, b)
        else:
            self.vecinos[X].append(Y)
            self.vecinos[Y].append(X)
        self.rel[X, Y] = ok
        self.rel[Y, X] = lambda b, a, f=ok: f(a, b)    # el mismo arco leído al revés

    def es_solucion(self, asignacion):
        return (len(asignacion) == len(self.variables)
                and all(asignacion[X] in self.dominios[X] for X in self.variables)
                and all(ok(asignacion[X], asignacion[Y]) for (X, Y), ok in self.rel.items()))

distinto = lambda a, b: a != b

def australia(orden=("WA", "NSW", "NT", "Q", "V", "SA", "T"), colores=("rojo", "verde", "azul")):
    csp = CSP(orden, {X: colores for X in orden})
    for X, Y in [("WA", "NT"), ("WA", "SA"), ("NT", "SA"), ("NT", "Q"), ("SA", "Q"),
                 ("SA", "NSW"), ("SA", "V"), ("Q", "NSW"), ("NSW", "V")]:
        csp.restringe(X, Y, distinto)
    return csp

aus = australia()
print("variables:", aus.variables)
print("restricciones:", len(aus.rel) // 2, "  arcos:", len(aus.rel))
print("vecinos de SA:", aus.vecinos["SA"])
print("¿solución?", aus.es_solucion({"WA": "rojo", "NT": "verde", "SA": "azul", "Q": "rojo",
                                      "NSW": "verde", "V": "rojo", "T": "rojo"}))

Each constraint is stored twice, once per direction, because AC-3 works with directed arcs: Australia’s 9 constraints are 18 arcs. Now revise and AC-3 as above, plus two experiments: the Australia example where forward checking falls short, and the queue figure’s three networks with 300 random revision orders.

[ ]revise, AC-3 and queue orderBrowser
from collections import deque
import random

def revise(csp, D, Xi, Xj, est):
    """Valores de D[Xi] sin soporte en D[Xj] (no los borra)."""
    ok, Dj = csp.rel[Xi, Xj], D[Xj]
    sin_soporte = []
    for a in D[Xi]:
        for b in Dj:
            est["comprobaciones"] += 1
            if ok(a, b):
                break                      # a tiene soporte: basta uno
        else:
            sin_soporte.append(a)
    return sin_soporte

def ac3(csp, D, cola=None, rastro=None, est=None):
    """AC-3 de Mackworth. Modifica D; devuelve False si algún dominio se vacía.
    cola: arcos iniciales (por defecto, todos). rastro: lista donde anotar (X, valor) borrados."""
    if est is None:
        est = {"comprobaciones": 0, "revisiones": 0}
    cola = deque(csp.rel) if cola is None else deque(cola)
    en_cola = set(cola)
    while cola:
        Xi, Xj = cola.popleft()
        en_cola.discard((Xi, Xj))
        est["revisiones"] += 1
        quitar = revise(csp, D, Xi, Xj, est)
        if quitar:
            for a in quitar:
                D[Xi].discard(a)
                if rastro is not None:
                    rastro.append((Xi, a))
            if not D[Xi]:
                return False
            for Xk in csp.vecinos[Xi]:     # los soportes de Xk en Xi pueden haber desaparecido
                if Xk != Xj and (Xk, Xi) not in en_cola:
                    cola.append((Xk, Xi))
                    en_cola.add((Xk, Xi))
    return True

copia = lambda csp: {X: set(v) for X, v in csp.dominios.items()}

# 1. Comprobación hacia delante frente a AC-3 tras WA = rojo y Q = verde
D = copia(aus)
D["WA"], D["Q"] = {"rojo"}, {"verde"}
for X, a in [("WA", "rojo"), ("Q", "verde")]:            # hacia delante: solo vecinos de lo asignado
    for Y in aus.vecinos[X]:
        D[Y] = {b for b in D[Y] if b != a}
print("hacia delante:", {X: sorted(D[X]) for X in ["NT", "SA", "NSW", "V"]})
est = {"comprobaciones": 0, "revisiones": 0}
print("AC-3 sobre ese estado:", ac3(aus, D, est=est), est)

# 2. El orden de la cola cambia el trabajo, no el resultado
def ac3_con_politica(csp, politica, semilla=0):
    D, est = copia(csp), {"comprobaciones": 0, "revisiones": 0}
    cola, rnd = list(csp.rel), random.Random(semilla)
    while cola:
        k = {"fifo": 0, "lifo": len(cola) - 1, "azar": rnd.randrange(len(cola))}[politica]
        Xi, Xj = cola.pop(k)
        est["revisiones"] += 1
        quitar = revise(csp, D, Xi, Xj, est)
        if quitar:
            D[Xi] -= set(quitar)
            if not D[Xi]:
                break
            for Xk in csp.vecinos[Xi]:
                if Xk != Xj and (Xk, Xi) not in cola:
                    cola.append((Xk, Xi))
    return tuple((X, tuple(sorted(v))) for X, v in D.items()), est["revisiones"]

def red(variables, valores, restricciones):
    csp = CSP(variables, {X: valores for X in variables})
    for X, Y, ok in restricciones:
        csp.restringe(X, Y, ok)
    return csp

menor = lambda a, b: a < b
redes = {
    "cuatro variables": red("ABCD", [1, 2, 3], [("A", "C", distinto), ("A", "B", distinto), ("B", "D", distinto),
                                                 ("B", "C", menor), ("A", "D", menor)]),
    "cadena A<B<C<D": red("ABCD", [1, 2, 3, 4], [("A", "B", menor), ("B", "C", menor), ("C", "D", menor)]),
    "triángulo, 2 colores": red("XYZ", ["r", "v"], [("X", "Y", distinto), ("Y", "Z", distinto), ("X", "Z", distinto)]),
}
for nombre, csp in redes.items():
    rf, nf = ac3_con_politica(csp, "fifo")
    rl, nl = ac3_con_politica(csp, "lifo")
    azar = [ac3_con_politica(csp, "azar", s) for s in range(300)]
    distintos = {r for r, _ in azar} | {rf, rl}
    revs = [n for _, n in azar]
    print(f"{nombre:21s} FIFO {nf:2d} rev.  LIFO {nl:2d} rev.  300 órdenes al azar: {min(revs)} a {max(revs)} rev.,"
          f" resultados distintos: {len(distintos)}  ->  {dict(rf)}")

Forward checking leaves NT=SA={azul}NT = SA = \{\text{azul}\} and AC-3 turns it into an empty domain in five revisions. On small networks work depends on order (10 to 16 revisions in the four-variable network, 6 to 12 in the chain) and the result is always the same: one distinct output among 302 runs, as predicted by the fixed-point theorem. In the four-variable network C={2,3}C = \{2, 3\} and D={2,3}D = \{2, 3\} remain although its only two solutions have C=D=3C = D = 3: arc-consistent does not mean every surviving value is in a solution. AC-3 solves the chain alone. In the triangle it removes nothing.

Now full backtracking, with all three heuristics, three inference levels and a hook for global-constraint propagators. Count every assignment made as a node and every assignment undone as a backtrack; if the solver finds a solution, nodes = variables + backtracks.

[ ]Backtracking with MRV, degree, LCV, forward checking and MACBrowser
def resolver(csp, variable="mrv", valor="lcv", inferencia="mac", propagador_global=None, max_nodos=10**6):
    """Backtracking cronológico. variable: 'estatico' | 'mrv' | 'mrv+grado'; valor: 'estatico' | 'lcv';
    inferencia: 'ninguna' | 'fc' | 'mac'. Devuelve (asignación, o None si no hay, o False si se agota el límite; estadísticas)."""
    D = {X: set(csp.dominios[X]) for X in csp.variables}
    asig = {}
    est = {"nodos": 0, "retrocesos": 0, "comprobaciones": 0, "revisiones": 0}

    def consistente(X, a):                                 # solo hace falta sin inferencia
        for Y in csp.vecinos[X]:
            if Y in asig:
                est["comprobaciones"] += 1
                if not csp.rel[X, Y](a, asig[Y]):
                    return False
        return True

    def restantes(X):                                      # valores legales que le quedan a X
        if inferencia == "ninguna":
            return sum(consistente(X, a) for a in D[X])
        return len(D[X])                                   # con inferencia, D ya está filtrado

    def elegir_variable():
        libres = [X for X in csp.variables if X not in asig]
        if variable == "estatico":
            return libres[0]
        if variable == "mrv":                              # fallar primero
            return min(libres, key=restantes)
        grado = lambda X: sum(Y not in asig for Y in csp.vecinos[X])
        return min(libres, key=lambda X: (restantes(X), -grado(X)))

    def ordenar_valores(X):
        vals = sorted(D[X])
        if valor == "estatico":
            return vals
        def descartes(a):                                  # cuántos valores quita a las vecinas libres
            n = 0
            for Y in csp.vecinos[X]:
                if Y not in asig:
                    ok = csp.rel[X, Y]
                    for b in D[Y]:
                        est["comprobaciones"] += 1
                        n += not ok(a, b)
            return n
        return sorted(vals, key=lambda a: (descartes(a), a))   # tener éxito primero

    def hacia_delante(X, a, rastro):
        for Y in csp.vecinos[X]:
            if Y in asig:
                continue
            ok = csp.rel[Y, X]
            for b in list(D[Y]):
                est["comprobaciones"] += 1
                if not ok(b, a):
                    D[Y].discard(b)
                    rastro.append((Y, b))
            if not D[Y]:
                return False
        return True

    def mac(X, rastro):
        cola = [(Y, X) for Y in csp.vecinos[X] if Y not in asig]
        if not ac3(csp, D, cola, rastro, est):
            return False
        while propagador_global is not None:               # restricciones globales hasta el punto fijo
            cambiadas = propagador_global(D, rastro)
            if cambiadas is None:
                return False                               # dominio vacío
            if not cambiadas:
                return True
            cola = [(Y, Z) for Z in cambiadas for Y in csp.vecinos[Z]]
            if not ac3(csp, D, cola, rastro, est):
                return False
        return True

    def bt():
        if len(asig) == len(csp.variables):
            return True
        if est["nodos"] >= max_nodos:
            return False
        X = elegir_variable()
        for a in ordenar_valores(X):
            if inferencia == "ninguna" and not consistente(X, a):
                continue
            est["nodos"] += 1
            rastro = [(X, b) for b in D[X] if b != a]      # todo lo que se borra se anota para deshacerlo
            D[X] = {a}
            asig[X] = a
            ok = (hacia_delante(X, a, rastro) if inferencia == "fc"
                  else mac(X, rastro) if inferencia == "mac" else True)
            if ok and bt():
                return True
            if est["nodos"] >= max_nodos:
                return False
            del asig[X]
            for Y, b in rastro:                            # restaurar los dominios al retroceder
                D[Y].add(b)
            est["retrocesos"] += 1
        return False

    encontrada = bt()
    if encontrada:
        return dict(asig), est
    return (False if est["nodos"] >= max_nodos else None), est

print(f"{'inferencia':10s} {'variable':10s} {'valor':8s} {'nodos':>5s} {'retrocesos':>10s} {'comprob.':>8s}")
for inferencia in ["ninguna", "fc", "mac"]:
    for variable in ["estatico", "mrv", "mrv+grado"]:
        sol, est = resolver(aus, variable, "estatico", inferencia)
        assert aus.es_solucion(sol)
        print(f"{inferencia:10s} {variable:10s} {'estatico':8s} {est['nodos']:5d} {est['retrocesos']:10d} {est['comprobaciones']:8d}")
sol, _ = resolver(aus, "estatico", "estatico", "ninguna")
print("\nsolución con el orden fijo:", sol)

With fixed order, inference reduces backtracks from 9 to 5 (forward checking) and 3 (MAC), and any MRV variant reaches a solution in 7 nodes, one per variable, without backtracking. Notice the checks column too: MRV without inference needs 53 to recalculate legal values at every node, while forward checking needs only 23. This is why MRV and forward checking nearly always go together in practice. The numbers match the map figure, which runs the same algorithm.

Hard sudokus

The binary sudoku model and root propagation for the figure’s three puzzles:

[ ]Sudoku as a binary CSPBrowser
import time

def sudoku(pistas):
    """81 variables (fila, columna), dominios {1..9} o la pista, y 810 restricciones binarias ≠."""
    celdas = [(f, c) for f in range(9) for c in range(9)]
    dom = {X: ({int(ch)} if ch != "." else set(range(1, 10))) for X, ch in zip(celdas, pistas)}
    csp = CSP(celdas, dom)
    for p, q in combinations(celdas, 2):
        if p[0] == q[0] or p[1] == q[1] or (p[0] // 3, p[1] // 3) == (q[0] // 3, q[1] // 3):
            csp.restringe(p, q, distinto)
    return csp

SUDOKUS = {
    "Wikipedia": "53..7....6..195....98....6.8...6...34..8.3..17...2...6.6....28....419..5....8..79",
    "Escargot":  "1....7.9..3..2...8..96..5....53..9...1..8...26....4...3......1..4......7..7...3..",
    "Inkala":    "8..........36......7..9.2...5...7.......457.....1...3...1....68..85...1..9....4..",
}
candidatos = lambda D: sum(len(v) for v in D.values())

for nombre, s in SUDOKUS.items():
    csp = sudoku(s)
    D_fc = copia(csp)                                   # hacia delante desde las pistas
    for X in csp.variables:
        if len(csp.dominios[X]) == 1:
            a = next(iter(csp.dominios[X]))
            for Y in csp.vecinos[X]:
                if len(csp.dominios[Y]) > 1:
                    D_fc[Y].discard(a)
    D_ac, est = copia(csp), {"comprobaciones": 0, "revisiones": 0}
    ac3(csp, D_ac, est=est)
    decididas = sum(len(v) == 1 for v in D_ac.values())
    print(f"{nombre:9s} pistas {sum(ch != '.' for ch in s)}  restricciones {len(csp.rel) // 2}  "
          f"candidatos: hacia delante {candidatos(D_fc)}, AC-3 {candidatos(D_ac)} "
          f"({est['revisiones']} revisiones, {decididas} celdas decididas)")

for nombre in ["Wikipedia", "Escargot"]:
    csp = sudoku(SUDOKUS[nombre])
    for inferencia in ["fc", "mac"]:
        t = time.perf_counter()
        sol, est = resolver(csp, "mrv", "estatico", inferencia)
        assert csp.es_solucion(sol)
        print(f"{nombre:9s} MRV + {inferencia:3s}: {est['nodos']:4d} nodos, {est['retrocesos']:3d} retrocesos, "
              f"{est['comprobaciones']:6d} comprobaciones, {time.perf_counter() - t:.2f} s")

In Escargot, MAC reduces backtracks from 159 to 22. Inkala’s is the hard case:

[ ]Inkala sudoku with forward checking and MACBrowser
inkala = sudoku(SUDOKUS["Inkala"])
for inferencia in ["fc", "mac"]:
    t = time.perf_counter()
    sol, est = resolver(inkala, "mrv", "estatico", inferencia)
    assert inkala.es_solucion(sol)
    print(f"Inkala MRV + {inferencia:3s}: {est['nodos']:5d} nodos, {est['retrocesos']:5d} retrocesos, "
          f"{est['comprobaciones']:7d} comprobaciones, {est['revisiones']:6d} revisiones, {time.perf_counter() - t:.1f} s")
print("\n".join(" ".join(str(sol[f, c]) for c in range(9)) for f in range(9)))

All different, for real

Binarized sudoku loses information. Consider the minimal pigeonhole case: three variables P,Q,RP, Q, R with domain {1,2}\{1, 2\} must all differ. As binary constraints, each constraint between two {1,2}\{1, 2\} domains is arc-consistent and AC-3 sees nothing; looking at all three, it is obvious three pigeons cannot fit in two holes. Generalized arc consistency (GAC) of an AllDifferent(X1,…,Xk)\text{AllDifferent}(X_1, \dots, X_k) constraint retains value aa of XiX_i only if an assignment of distinct values to all constraint variables exists with Xi=aX_i = a; that is a bipartite matching between variables and values covering every variable, decided using augmenting paths (Hall’s theorem gives the existence condition). Régin’s (1994) efficient filtering is in the next lesson; here the direct version suffices: one matching per (variable, value) pair.

[ ]GAC for all-different using matchingsBrowser
def hay_emparejamiento(U, D, X0, a0):
    """¿Pueden las variables de U tomar valores distintos de sus dominios con X0 = a0? (caminos aumentantes)"""
    duenyo = {}                                         # valor -> variable que lo usa
    def colocar(X, vistos):
        for a in ([a0] if X == X0 else D[X]):
            if (a == a0 and X != X0) or a in vistos:
                continue
            vistos.add(a)
            if a not in duenyo or colocar(duenyo[a], vistos):
                duenyo[a] = X
                return True
        return False
    return all(colocar(X, set()) for X in U)

def gac_todos_distintos(unidades):
    """Propagador de las restricciones «todos distintos»: borra a de X si ningún emparejamiento lo usa."""
    def propagar(D, rastro):
        cambiadas = []
        for U in unidades:
            for X in U:
                for a in list(D[X]):
                    if not hay_emparejamiento(U, D, X, a):
                        D[X].discard(a)
                        rastro.append((X, a))
                        cambiadas.append(X)
                        if not D[X]:
                            return None
        return cambiadas
    return propagar

# el palomar: tres variables, dos valores
palomar = red("PQR", [1, 2], [("P", "Q", distinto), ("Q", "R", distinto), ("P", "R", distinto)])
D = copia(palomar)
print("palomar, AC-3 binario:", ac3(palomar, D), {X: sorted(v) for X, v in D.items()})
print("palomar, GAC de todos distintos:", gac_todos_distintos([list("PQR")])(copia(palomar), []))

UNIDADES = ([[(f, c) for c in range(9)] for f in range(9)] + [[(f, c) for f in range(9)] for c in range(9)]
            + [[(3 * bf + i, 3 * bc + j) for i in range(3) for j in range(3)] for bf in range(3) for bc in range(3)])
gac = gac_todos_distintos(UNIDADES)
for nombre in ["Escargot", "Inkala"]:
    csp = sudoku(SUDOKUS[nombre])
    D = copia(csp)
    ac3(csp, D); gac(D, []); ac3(csp, D)
    t = time.perf_counter()
    sol, est = resolver(csp, "mrv", "estatico", "mac", propagador_global=gac)
    assert csp.es_solucion(sol)
    print(f"{nombre:9s} candidatos tras AC-3 + GAC en la raíz: {candidatos(D)};  MRV + MAC + GAC: "
          f"{est['nodos']} nodos, {est['retrocesos']} retrocesos, {time.perf_counter() - t:.1f} s")

The pigeonhole returns None: empty domain, inconsistency detected without search where AC-3 removed nothing. In sudokus, root GAC barely changes anything (Escargot goes from 246 to 240 candidates; Inkala stays at 275), but during search it is another story: in Inkala, MAC with GAC needs 97 backtracks versus binary MAC’s 3306, 34 times fewer. GAC deduces what enthusiasts call hidden singles (the only cell in a row admitting 4) and much more, and these deductions arise as soon as search fixes a few cells. This is the difference between decomposing a global constraint into binaries and propagating it whole.

nn queens: an ablation

To measure each piece’s contribution, the same table with 25 queens and all reasonable combinations. Rows without MRV or LCV exhaust the 2000-node limit (marked “>”). LCV is combined only with inference: without it domains do not reflect which values actually remain.

[ ]25-queens ablationBrowser
def reinas(n):
    """Una variable por columna (su valor es la fila): la restricción de columnas se cumple por construcción."""
    csp = CSP(range(n), {i: range(n) for i in range(n)})
    for i, j in combinations(range(n), 2):
        csp.restringe(i, j, lambda a, b, d=j - i: a != b and abs(a - b) != d)
    return csp

def ablacion(csp, configs, max_nodos):
    print(f"{'inferencia':10s} {'variable':9s} {'valor':8s} {'nodos':>7s} {'retrocesos':>10s} {'comprob.':>9s} {'tiempo':>7s}")
    for inferencia, variable, valor in configs:
        t = time.perf_counter()
        sol, est = resolver(csp, variable, valor, inferencia, max_nodos=max_nodos)
        nodos = f"{est['nodos']}" if sol else f">{max_nodos}"
        if sol:
            assert csp.es_solucion(sol)
        print(f"{inferencia:10s} {variable:9s} {valor:8s} {nodos:>7s} {est['retrocesos']:10d} "
              f"{est['comprobaciones']:9d} {time.perf_counter() - t:6.2f}s")

ablacion(reinas(25), [("ninguna", "estatico", "estatico"), ("ninguna", "mrv", "estatico"),
                      ("fc", "estatico", "estatico"), ("fc", "estatico", "lcv"),
                      ("fc", "mrv", "estatico"), ("fc", "mrv", "lcv"),
                      ("mac", "estatico", "estatico"), ("mac", "mrv", "estatico"), ("mac", "mrv", "lcv")], max_nodos=2000)

The table tells the whole story:

  • Without heuristics nothing works: pure backtracking, with forward checking or MAC, exhausts the limit.
  • MRV is decisive: 275 nodes and 250 backtracks without inference, the same with forward checking (same nodes because binary constraints give the same legal values, but 8776 checks instead of 384743) and 96 nodes with MAC.
  • LCV also helps greatly: alone with forward checking it drops to 714 nodes; with MRV, all 25 queens are placed without a single backtrack (25 nodes), with forward checking or MAC.
  • Every improvement costs checks: LCV inspects every free neighbor’s domain for each value. With MRV and forward checking it increases from 8776 checks to 70504 in exchange for eliminating all backtracks.

And the design goal, one hundred queens in the browser, using the cheapest working combination:

[ ]One hundred queens with MRV and forward checkingBrowser
cien = reinas(100)
t = time.perf_counter()
sol, est = resolver(cien, "mrv", "estatico", "fc")
print(f"n = 100, MRV + hacia delante: {est['nodos']} nodos, {est['retrocesos']} retrocesos, "
      f"{est['comprobaciones']} comprobaciones, {time.perf_counter() - t:.1f} s;  ¿solución? {cien.es_solucion(sol)}")
filas = [sol[i] for i in range(100)]
print("filas de las 20 primeras columnas:", filas[:20])

185 nodes and 85 backtracks in a space of 100100100^{100} complete assignments. The naive tree without commutativity would have 100!⋅100100100!\cdot 100^{100} leaves. For large nn queens get easier, not harder, because solutions are plentiful; the next lesson’s min-conflicts local search solves one million queens in about 50 steps on average after initialization (Minton et al., 1992).

The professional version: OR-Tools CP-SAT

CP-SAT, Google’s OR-Tools constraint solver, is a de facto industry standard and has won gold in several MiniZinc Challenge categories in recent years (for example, 2024 and 2025). It is not backtracking with MAC: it translates the model to Boolean variables, propagates with constraint-specific algorithms, learns clauses from every conflict like a modern SAT solver (see CSP-to-SAT encodings and CDCL), and combines this with linear relaxations and local search. This part runs on your machine (runtime=local) because OR-Tools does not work in the browser. Install it with pip install ortools. First, a hidden cell repeats required definitions from earlier cells in the local process.

Sudoku in CP-SAT takes ten lines: one integer variable per cell and 27 add_all_different. We solve it on one thread, for fair comparison with our solver (also single-threaded), and request the search log.

[ ]Sudoku in CP-SATLocal GPU
from ortools.sat.python import cp_model

def sudoku_cpsat(pistas, registro=False):
    m = cp_model.CpModel()
    x = {(f, c): m.new_int_var(1, 9, f"x{f}{c}") for f in range(9) for c in range(9)}
    for (f, c), ch in zip(x, pistas):
        if ch != ".":
            m.add(x[f, c] == int(ch))
    for i in range(9):
        m.add_all_different([x[i, c] for c in range(9)])          # filas
        m.add_all_different([x[f, i] for f in range(9)])          # columnas
        bf, bc = 3 * (i // 3), 3 * (i % 3)
        m.add_all_different([x[bf + a, bc + b] for a in range(3) for b in range(3)])   # cajas
    solver = cp_model.CpSolver()
    solver.parameters.num_workers = 1             # un hilo, como nuestro solver
    lineas = []
    if registro:
        solver.parameters.log_search_progress = True
        solver.parameters.log_to_stdout = False
        solver.log_callback = lambda s: lineas.extend(s.splitlines())
    estado = solver.solve(m)
    sol = {k: solver.value(v) for k, v in x.items()} if estado in (cp_model.OPTIMAL, cp_model.FEASIBLE) else None
    return sol, solver, lineas

for nombre, s in SUDOKUS.items():
    csp = sudoku(s)
    t = time.perf_counter()
    sol, est = resolver(csp, "mrv", "estatico", "mac")
    t_propio = time.perf_counter() - t
    t = time.perf_counter()
    sol_cp, solver, _ = sudoku_cpsat(s)
    t_cp = time.perf_counter() - t
    assert csp.es_solucion(sol_cp) and sol_cp == sol
    print(f"{nombre:9s} MRV + MAC propio: {est['retrocesos']:5d} retrocesos, {t_propio:6.3f} s   "
          f"CP-SAT: {solver.num_conflicts:3d} conflictos, {t_cp:6.3f} s   cociente de tiempos {t_propio / t_cp:5.1f}")

_, solver, lineas = sudoku_cpsat(SUDOKUS["Inkala"], registro=True)
print(f"\nregistro de CP-SAT en Inkala ({len(lineas)} líneas); algunas:")
for i, l in enumerate(lineas):
    s = l.strip()
    if (any(k in s for k in ("all_diff: permutation expanded", "new_bool: integer encoding", "#kExactlyOne", "Booleans in"))
            or s.startswith(("#Variables:", "status:", "conflicts:", "branches:", "propagations:"))):
        print("  ", s[:118])
    if s.startswith("Search stats"):                  # cabecera y fila de la tabla de búsqueda
        print("  ", s[:118])
        print("  ", lineas[i + 1].strip()[:118])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

All three solutions match our solver’s (the cell checks). On Inkala’s sudoku CP-SAT needs a few dozen conflicts where binary MAC backtracks 3306 times, and takes tens of times less; exact timing ratios depend on machine and load and will appear in your run. The log explains why. In presolve the 27 all_diff: permutation expanded constraints are recognized as permutations (nine variables, nine values) and each integer variable is encoded with one Boolean literal per value (new_bool: integer encoding); the resulting model has exactly one constraints on those literals (#kExactlyOne): “the cell has exactly one value” and “each digit appears exactly once in each unit.” The latter family sees precisely the hidden singles binary AC-3 misses. Search (Search stats) then learns one clause per conflict, avoiding the same mistake on other branches.

An exam timetable

The motivating case: 50 exams, 200 students taking 3 subjects each (some more popular than others), 9 slots and 80 seats per slot. Two very different constraints: clashes (exams with a shared student cannot coincide) are binary; capacity (the sum of students in a slot is at most 80) is a linear constraint over all exams at once.

[ ]Exam timetable: custom solver versus CP-SATLocal GPU
import random

rnd = random.Random(7)
E, N_EST, CAP, T = 50, 200, 80, 9                 # CAP: plazas por franja; T: franjas disponibles
peso = [1 / (k + 1) ** 0.3 for k in range(E)]       # unas asignaturas son más populares que otras
matricula = [set() for _ in range(N_EST)]
for s in matricula:
    while len(s) < 3:
        s.add(rnd.choices(range(E), weights=peso)[0])
tam = [sum(e in s for s in matricula) for e in range(E)]
choques = sorted({(a, b) for s in matricula for a in s for b in s if a < b})
print(f"{E} exámenes, {len(choques)} pares que comparten estudiantes, de {min(tam)} a {max(tam)} estudiantes por examen, "
      f"{sum(tam)} plazas en total; {T} franjas de {CAP} plazas")

# 1. Nuestro solver solo sabe de restricciones binarias: resuelve los choques y no ve la capacidad
csp = CSP(range(E), {e: range(T) for e in range(E)})
for a, b in choques:
    csp.restringe(a, b, distinto)
t = time.perf_counter()
sol, est = resolver(csp, "mrv+grado", "lcv", "mac")
ocup = [sum(tam[e] for e in range(E) if sol[e] == f) for f in range(T)]
print(f"solver propio, {T} franjas sin choques en {est['nodos']} nodos ({time.perf_counter() - t:.3f} s); "
      f"ocupación {ocup} -> {'cabe' if max(ocup) <= CAP else 'NO cabe'}")

# 2. CP-SAT: choques, capacidad (una suma por franja) y minimizar la última franja usada
def horario_cpsat(T_max):
    m = cp_model.CpModel()
    x = [m.new_int_var(0, T_max - 1, f"x{e}") for e in range(E)]
    for a, b in choques:
        m.add(x[a] != x[b])
    en = {(e, f): m.new_bool_var(f"en{e}_{f}") for e in range(E) for f in range(T_max)}
    for e in range(E):
        m.add_exactly_one(en[e, f] for f in range(T_max))
        for f in range(T_max):
            m.add(x[e] == f).only_enforce_if(en[e, f])    # en[e, f] => x[e] = f
    for f in range(T_max):
        m.add(sum(tam[e] * en[e, f] for e in range(E)) <= CAP)
    ultima = m.new_int_var(0, T_max - 1, "ultima")
    m.add_max_equality(ultima, x)
    m.minimize(ultima)
    solver = cp_model.CpSolver()
    solver.parameters.num_workers = 1
    solver.parameters.max_time_in_seconds = 120
    estado = solver.solve(m)
    return solver, estado, x

t = time.perf_counter()
solver, estado, x = horario_cpsat(12)
asig = [solver.value(v) for v in x]
T_cp = max(asig) + 1
ocup = [sum(tam[e] for e in range(E) if asig[e] == f) for f in range(T_cp)]
assert all(asig[a] != asig[b] for a, b in choques) and max(ocup) <= CAP
print(f"CP-SAT: {solver.status_name(estado)}, {T_cp} franjas, ocupación {ocup}; "
      f"{solver.num_conflicts} conflictos, {time.perf_counter() - t:.2f} s")
print(f"cota de capacidad: ceil({sum(tam)} / {CAP}) = {-(-sum(tam) // CAP)} franjas")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

There are 449 exam pairs that cannot coincide. Our solver finds a clash-free 9-slot timetable in 50 nodes, but several slots exceed 80 seats (the fullest has 89): capacity sums many exams and our binary model cannot express it. CP-SAT expresses it in one line per slot, finds a 9-slot timetable that fits classrooms and proves (status OPTIMAL) that 8 is impossible, although capacity bound ⌈600/80⌉=8\lceil 600 / 80\rceil = 8 did not rule it out. That proof is the expensive part: tens of thousands of conflicts and tens of seconds on one thread. If you remove num_workers = 1, CP-SAT uses all cores with different strategies in parallel.

The classical operations-research alternative for such problems is integer linear programming: binary variables xe,tx_{e,t}, the same constraints as linear inequalities, and branch-and-bound over the linear programming relaxation. It is strong when the linear relaxation gives good bounds (capacities, costs) and weak with disjunctions such as Te≠TfT_e \neq T_f, where constraint propagation shines. CP-SAT uses both.

Common mistakes

Exercises

NumericLeaves in the naive tree
A CSP has n=4n = 4 variables, each with domain size d=3d = 3. If formulated as search where each action assigns a value to any still-free variable (without exploiting commutativity) and nothing is pruned, how many leaves does the search tree have?
NumericSudoku's initial queue
In binarized sudoku, each pair of cells sharing a row, column or box has a ≠\neq constraint. How many directed arcs are in AC-3's initial queue?
QuizWhat forward checking misses
On the three-color Australia map, assign WA=rojoWA = \text{rojo} and then Q=verdeQ = \text{verde}, with forward checking after each. What happens then?
QuizFail first, succeed first
MRV chooses the variable with fewest legal values (‘most likely to fail’), while LCV chooses the value leaving most options (‘most likely to work’). Why the asymmetry?
QuizThe two-color triangle
Three variables X,Y,ZX, Y, Z have domain {r,v}\{r, v\} and constraints X≠YX \neq Y, Y≠ZY \neq Z, X≠ZX \neq Z. Which statement is correct?
QuizAn incorrectly undone trail
A forward-checking solver records deleted values on its trail, but a bug restores only the assigned variable's domain on backtracking, not its neighbors'. What is the characteristic symptom?
NumericHow often can an arc enter the queue?
In AC-3 (which does not queue an already queued arc and stops as soon as a domain is emptied), variable XiX_i starts with ∣Di∣=d\abs{D_i} = d. At most how many times can arc (Xk,Xi)(X_k, X_i) enter the queue throughout execution? Answer for d=5d = 5.
ProofAC-3 terminates and its result is order-independent
Prove: Let D⋆D^\star be the greatest arc-consistent subdomain contained in initial domains D0D^0 (it exists because the union of arc-consistent subdomains is arc-consistent). Then AC-3, under any queue policy, terminates after O(ed)\bigO(ed) revisions and O(ed3)\bigO(ed^3) checks and, if it empties no domain, returns exactly D⋆D^\star.
0
Call the current domains DD and the queue QQ. Recall that when revise(Xi,Xj)\text{revise}(X_i, X_j) deletes something from DiD_i, AC-3 queues (Xk,Xi)(X_k, X_i) for every neighbor Xk≠XjX_k \neq X_j of XiX_i not already queued.

Step 1 of 4. Why does AC-3 terminate?

Coderevise and AC-3
Implement revise(rel, D, Xi, Xj), which deletes from D[Xi] values without support in D[Xj] and returns True if it deleted any, and ac3(vecinos, rel, D), which enforces arc consistency by modifying D and returns False if a domain becomes empty, True otherwise. D is a dictionary of sets, vecinos[X] lists variables sharing a constraint with X, and rel[(X, Y)] is an ok(a, b) function indicating whether X = a and Y = b are compatible (defined in both directions). Tests check random networks for arc consistency, preservation of every value in brute-force solutions, and the greatest arc-consistent subdomain.
from collections import deque

def revise(rel, D, Xi, Xj):
  """Borra de D[Xi] los valores sin soporte en D[Xj]; devuelve True si borró alguno."""
  # tu código
  return False

def ac3(vecinos, rel, D):
  """Consistencia de arco sobre D (se modifica). False si algún dominio queda vacío."""
  # tu código: cola con todos los arcos; al borrar en Xi, encola (Xk, Xi) para Xk != Xj
  return True
Shift+Enter to run

Summary

Key idea
A CSP opens the black box of state: with variables, domains and constraints, search can choose where to branch (fail first on variables, succeed first on values) and deduce without branching (propagate); together they reduce spaces of 105710^{57} assignments to a few thousand nodes.
  • A CSP is (X,D,C)(\mathcal{X}, \mathcal{D}, \mathcal{C}) with finite domains; deciding whether a solution exists is NP-complete. Good modeling (queens by column, carries in cryptarithmetics, global rather than binary constraints) is the first optimization.
  • Assignment commutes: choosing one variable per node reduces the tree from n! dnn!\,d^n to dnd^n leaves without losing completeness. That is backtracking.
  • MRV and degree choose the variable most likely to fail; LCV the value leaving most options. Variable order changes the entire tree; value order matters only if one solution suffices.
  • Forward checking filters neighbors of the last assigned variable and misses conflicts between free variables. AC-3 enforces arc consistency: it is sound, converges to the greatest arc-consistent subdomain under any queue order, and costs O(ed3)\bigO(ed^3); AC-4 and AC-2001 reduce this to optimal O(ed2)\bigO(ed^2).
  • MAC runs AC-3 after each assignment and prunes at least as much as forward checking; global constraints with GAC prune much more (3306 to 97 backtracks on Inkala’s sudoku). Backtracking must restore everything propagated.
  • Arc consistency is not global consistency (the two-color triangle). Strong kk-consistency with kk greater than graph width guarantees backtrack-free search; on trees arc consistency suffices.