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 in cell ,” 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 (, ) or a specialized algorithm. The space of complete assignments has elements, if all domains have size ; a sudoku with 60 empty cells has .
Five models
Australia coloring. Russell and Norvig’s textbook example. Variables: the seven states and territories, . Domains: . Constraints: regions sharing a border have different colors, nine in total (, , , , , , , , ). Tasmania touches none. This is graph coloring.
Sudoku. 81 variables, one per cell. Domain , 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 for each pair sharing a unit; an exercise asks how many.
queens. Place queens on an board without attacks. The good model does not use one variable per square: it uses variable per column, whose value is that column’s queen’s row. “One queen per column” is satisfied by construction and only binary constraints remain, and .
Cryptarithmetic. In each letter is a distinct digit and leading digits are not 0. A naive model uses the eight letters and one enormous constraint, . A model that propagates better adds carries and writes one equation per column, as in addition by hand:
Each equation touches at most five variables and the solver can reason with it once only a few are fixed: the last immediately forces because and a carry is at most 1. The unique solution is .
Exam timetables. One variable per exam, with available slots as its domain. Two exams sharing a student cannot coincide: , graph coloring again. Each slot holds at most students: , where 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 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 (): 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 (): 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” (), “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 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 : with , whose allowed relation is .
- Hidden variable. Add variable whose domain is the three tuples of , and three binary constraints saying “ is ‘s first component,” “ the second,” and “ 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 : , ‘s dual variable has domain and the constraint between both duals requires and 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 . 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: tuples for a sudoku row. We return to this with numbers.
Backtracking: why commutativity removes factor
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 .
At depth , variables remain free and each admits values, so the branching factor is and the tree has
leaves, although only distinct complete assignments exist. Each assignment appears times, once for each possible order of its choices. The remedy is that assignment commutes: 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 remain and the node chooses , every complete extension assigns exactly one value , thus extends exactly one child, that of ; by induction it appears at exactly one leaf in that child’s subtree. Counting leaves counts complete assignments: .
∎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 recursion levels plus what is needed to undo inferences; worst-case time is 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).
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 (the solver tries colors alphabetically), the variable with fewest legal values is a neighbor of , or , with two colors each, not , which retains all three. MRV first “closes” the map’s core around , 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 and . Forward checking leaves (neighbor of both) and (also neighbor of both). But and are neighbors and cannot both be blue: the partial assignment is already doomed, but forward checking cannot see it because the edge between and 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 and alone. For to be possible, needs some compatible value, and its only one, blue, is not compatible.
If a value has no support in , no solution can use it: any solution with would give a value from , none compatible. Removing it is safe. The operation removing unsupported values from an arc is , 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 ? Because supports for ‘s values were in , and just shrank: a value of may have lost support. Why not ? This subtlety appears in the guided exercise. In Australia, after and and forward checking, AC-3 revises : ‘s blue has no support, becomes empty and the branch is pruned immediately.
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 and are arc-consistent, their componentwise union is too: a value of coming from has support in , and likewise if it comes from . Since finitely many subdomains exist, the union of all arc-consistent ones contained in is arc-consistent and contains them all: it is . That AC-3 returns regardless of order is the final guided exercise: one invariant shows AC-3 never deletes a value of and another that the result is arc-consistent once the queue is empty.
(3) Arc enters the queue initially and thereafter only when shrinks; the precise count is also in the exercises. Each entry causes a revision comparing each of at most values of against at most of : checks.
∎Point (2) is a special case of a general fact: operations 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 constraints and propagation visible by eye. With constraints, deletes something only when has a single value : then disappears from . 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.
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 comes from each revision searching again from scratch for supports already found. Two classical ways avoid this, both reaching , optimal in the general case: to establish that a value has no support under an arbitrary relation, inspect its possible partners, and there are (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 and each it stores a support counter in , and for each the list of values it supports. On deleting it traverses that list and decrements counters; a counter reaching 0 deletes its value. Time and memory . The drawback is that initialization always costs , 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 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 and memory . Bessière, Régin, Yap and Zhang (2005) proved worst-case optimality.
In practice something else matters: many constraints admit a specialized much cheaper than the generic one. For it suffices to check whether ; for compare with . Real solvers use no table of checks: each constraint brings its own propagator.
MAC: propagation during search
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 changed, it queues arcs pointing to , 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 forward checking deletes neighbor values incompatible with , exactly those deleted by MAC’s 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 -consistency
Arc consistency is local to each constraint. Its limit appears in the smallest example: three variables with domain and constraints , , , a two-color triangle. Every value has support on every arc ( in is supported by in , 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 cannot be extended to : the network is not 3-consistent. A path-consistency algorithm removes that pair from the relation between and , and also ; 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 ; 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 have a consistent assignment. has neighbors among them. The assignment restricted to those neighbors is consistent (part of a consistent assignment), and by -consistency, available because and consistency is strong, there is a value of compatible with them all. shares no constraints with the other earlier variables, so the extended assignment is consistent. If , need only be nonempty, which is 1-consistency.
∎Two consequences. A network of variables that is strongly -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 -consistency with large ? Because time and memory are exponential in (the assignments of 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.
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.
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 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 and remain although its only two solutions have : 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.
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:
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(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 with domain must all differ. As binary constraints, each constraint between two 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 constraint retains value of only if an assignment of distinct values to all constraint variables exists with ; 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.
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.
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.
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:
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 complete assignments. The naive tree without commutativity would have leaves. For large 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.
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])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.
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")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 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 , 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 , where constraint propagation shines. CP-SAT uses both.
Common mistakes
Exercises
Step 1 of 4. Why does AC-3 terminate?
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 TrueSummary
- A CSP is 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 to 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 ; AC-4 and AC-2001 reduce this to optimal .
- 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 -consistency with greater than graph width guarantees backtrack-free search; on trees arc consistency suffices.