Suppose Monday brings a sensor-zone fault-isolation puzzle, Wednesday brings a partial experimental-design Latin square, and Friday brings a VLSI geometric placement or Sudoku constraint problem. One could write three backtracking solvers from scratch; alternatively, all three problems can be translated into exact cover and solved by Knuth’s (2000) Algorithm X. This is Mental Move #19, Compile New Constraints into Exact Cover: express every ‘must-happen-once’ rule as a primary element, every ‘at-most-once’ mutex rule as a secondary element, and let minimum-remaining-values (MRV) branching prune the search tree. In this lecture, you will master reductions_constraints.exact_cover_algorithm_x, recover the OEIS -Queens sequence via reduce_n_queens_to_exact_cover, complete partial experimental blocks via reduce_latin_square_completion, and quantify the power of MRV column selection.
Learning objectives¶
Formulate Exact Cover () and execute Knuth’s Algorithm X (
reductions_constraints.exact_cover_algorithm_x) on canonical set-partitioning benchmarks.Distinguish primary (‘covered exactly once’) from secondary (‘covered at most once’) constraints in Generalized Exact Cover (
reduce_n_queens_to_exact_cover).Compile multi-rule combinatorial designs such as Latin squares (
reduce_latin_square_completion) and Sudoku into pure 0-1 incidence matrices without modifying a line of the solver.Prove and benchmark why Knuth’s S-heuristic (Minimum Remaining Values, MRV) reduces backtracking node expansions by orders of magnitude compared to fixed column ordering.
Time: about 60 min
try: # use the installed package, or the copy in this repository
import engthink
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engthink" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engthink.git"], check=True)
import engthink
import inspect
import math
import numpy as np
import matplotlib.pyplot as plt
from engthink import (constants_benchmarks, divide_spatial, dynamic_optimality, emergence_verification,
greedy_heuristic_search, information_streams, invariants_complexity, reductions_constraints,
representation_scaling)
from engthink.plotting import label_panels, log_ticks, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))1. Exact Cover & Knuth’s Algorithm X: One Engine for Exact Partitioning¶
Given a finite universe of primary elements and a collection of candidate subsets , the Exact Cover Problem asks for a subcollection of subsets that partitions —covering every primary element once and only once. Stacking subsets as rows of a binary matrix , we seek such that:
Knuth’s Algorithm X solves Equation (1.1) recursively:
If , record the current subset selection as an exact cover.
MRV Branching (S-heuristic): Pick an uncovered primary column covered by the fewest remaining active rows (if 0 rows cover , backtrack immediately).
For each candidate row covering , include , delete all columns in and every competing row sharing any element with , and recurse.
heading("Demonstration 1: Knuth's (2000) canonical {1..7} trace and sensor-zone partitioning")
mm19 = [m for m in constants_benchmarks.MENTAL_MOVES_DB if m["id"] == 19][0]
print(f"Mental Move #{mm19['id']} ({mm19['name']}): {mm19['invariant']}")
# 1. Donald Knuth's (2000) 'Dancing Links' paper exact example on universe {1, 2, 3, 4, 5, 6, 7}:
knuth_u = [1, 2, 3, 4, 5, 6, 7]
knuth_subs = {
"A": [1, 4, 7],
"B": [1, 4],
"C": [4, 5, 7],
"D": [3, 5, 6],
"E": [2, 3, 6, 7],
"F": [2, 7],
}
res_knuth = reductions_constraints.exact_cover_algorithm_x(knuth_u, knuth_subs)
assert res_knuth["solution_count"] == 1
assert sorted(res_knuth["solutions"][0]) == ["B", "D", "F"] # {1,4} U {3,5,6} U {2,7} = {1..7}!
# 2. Engineering reduction: Partitioning 8 reactor monitoring zones across non-interfering sensor modules:
zones = [f"Z{i}" for i in range(1, 9)]
radio_channels = ["CH_alpha", "CH_beta", "CH_gamma", "CH_delta"] # Secondary mutex: at most 1 module per channel
sensor_modules = {
"Mod_NorthA": ["Z1", "Z2", "Z5", "CH_alpha"],
"Mod_NorthB": ["Z1", "Z2", "CH_beta"],
"Mod_EastA": ["Z3", "Z4", "CH_beta"],
"Mod_EastB": ["Z3", "Z4", "Z6", "CH_alpha"],
"Mod_SouthA": ["Z5", "Z7", "Z8", "CH_gamma"],
"Mod_SouthB": ["Z6", "Z7", "Z8", "CH_delta"],
"Mod_WestA": ["Z5", "Z6", "CH_gamma"],
"Mod_Core": ["Z7", "Z8", "CH_delta"],
}
res_sens = reductions_constraints.exact_cover_algorithm_x(zones, sensor_modules, secondary_elements=radio_channels)
assert res_sens["solution_count"] == 2
for sol in res_sens["solutions"]:
covered_z = [e for k in sol for e in sensor_modules[k] if e.startswith("Z")]
used_ch = [e for k in sol for e in sensor_modules[k] if e.startswith("CH_")]
assert sorted(covered_z) == sorted(zones) # Every zone covered ONCE
assert len(used_ch) == len(set(used_ch)) # Every radio channel used AT MOST ONCE
print(f"Knuth {{1..7}} exact cover : {res_knuth['solutions']} found in {res_knuth['search_nodes']} search nodes")
print(f"Reactor sensor deployments : {res_sens['solutions']} (verified zero zone overlap & zero radio collisions)")
# Visualize Knuth's binary incidence matrix A and highlight exact-cover rows B, D, F:
row_names = list(knuth_subs.keys())
inc_mat = np.zeros((len(row_names), len(knuth_u)), dtype=int)
for r_i, rk in enumerate(row_names):
for elem in knuth_subs[rk]:
inc_mat[r_i, elem - 1] = 2 if rk in ("B", "D", "F") else 1
fig, ax = plt.subplots(figsize=(6.8, 3.6))
ax.imshow(inc_mat, cmap="YlGnBu", aspect="auto", vmin=0, vmax=2)
ax.set_xticks(range(7))
ax.set_xticklabels([str(x) for x in knuth_u])
ax.set_yticks(range(len(row_names)))
ax.set_yticklabels([f"{rk} {'<- COVER' if rk in ('B','D','F') else ''}" for rk in row_names])
ax.set_xlabel(r"Primary universe element $e \in \{1..7\}$")
ax.set_ylabel("Candidate subset")
ax.set_title("Knuth's example: rows B, D and F cover every column once")
ax.grid(False)
plt.show()
Demonstration 1: Knuth's (2000) canonical {1..7} trace and sensor-zone partitioning
===================================================================================
Mental Move #19 (Compile New Constraints into Exact Cover): Branch on primary constraint with minimum options
Knuth {1..7} exact cover : [['B', 'D', 'F']] found in 5 search nodes
Reactor sensor deployments : [['Mod_NorthA', 'Mod_EastA', 'Mod_SouthB'], ['Mod_NorthB', 'Mod_EastB', 'Mod_SouthA']] (verified zero zone overlap & zero radio collisions)

Figure 10.1. Incidence matrix of Knuth’s exact-cover example: rows are the candidate subsets A to F, columns the elements 1 to 7. The selected rows B, D and F (dark) cover every column exactly once.
What Demonstration 1 shows. Column 1 is covered only by A and B (branching factor 2), so the first decision considers two of the six rows, and the whole search takes 5 nodes.
2. Primary vs. Secondary Constraints: Compiling -Queens (reduce_n_queens_to_exact_cover)¶
How do you place non-attacking queens on an board without writing a custom chessboard solver? Look at the constraints on placing a queen at :
Primary constraints ( columns, covered exactly once): Every row
R0..R{N-1}must hold a queen, and every columnC0..C{N-1}must hold a queen.Secondary constraints ( diagonals, covered at most once): Each diagonal and anti-diagonal can hold 0 or 1 queen—many diagonals remain empty ().
heading("Demonstration 2: Compiling N-queens into generalized exact cover (OEIS A000170)")
oeis_a000170 = [1, 0, 0, 2, 10, 4, 40, 92] # Exact N-Queens counts for N = 1..8
counts_nq = []
nodes_nq = []
for n_val in range(1, 9):
nq_res = reductions_constraints.reduce_n_queens_to_exact_cover(n_val, max_solutions=500)
counts_nq.append(nq_res["solution_count"])
nodes_nq.append(nq_res["search_nodes"])
assert counts_nq == oeis_a000170
# Extract and verify one 8-Queens solution board:
sol8 = reductions_constraints.reduce_n_queens_to_exact_cover(8, max_solutions=1)["solutions"][0]
board8 = np.zeros((8, 8), dtype=int)
rc_list = []
for tok in sol8:
r_s, c_s = tok.strip("Q()").split(",")
ri, ci = int(r_s), int(c_s)
board8[ri, ci] = 1
rc_list.append((ri, ci))
assert np.all(np.sum(board8, axis=0) == 1) and np.all(np.sum(board8, axis=1) == 1)
assert len({r - c for r, c in rc_list}) == 8 and len({r + c for r, c in rc_list}) == 8
print("N = 1..8 Exact Cover solutions :", counts_nq, "(100% match with OEIS A000170)")
print("N = 1..8 Algorithm X nodes :", nodes_nq)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.0, 3.8))
checker = (np.arange(8)[:, None] + np.arange(8)[None, :]) % 2
ax1.imshow(checker, cmap="Greys", vmin=-0.5, vmax=2.0)
for ri, ci in rc_list:
ax1.scatter([ci], [ri], s=180, marker="*", c="#C0392B", edgecolors="black", zorder=5)
ax1.set_title("First 8-queens solution")
ax1.set_xlabel("Column $c$")
ax1.set_ylabel("Row $r$")
ax1.grid(False)
ns_arr = np.arange(1, 9)
ax2.bar(ns_arr, counts_nq, color="#2166AC", width=0.6)
ax2.set_xticks(ns_arr)
ax2.set_xlabel("Board dimension $N$")
ax2.set_ylabel("Exact distinct solutions")
ax2.set_title("Number of solutions (OEIS A000170)")
label_panels(fig)
plt.show()
Demonstration 2: Compiling N-queens into generalized exact cover (OEIS A000170)
===============================================================================
N = 1..8 Exact Cover solutions : [1, 0, 0, 2, 10, 4, 40, 92] (100% match with OEIS A000170)
N = 1..8 Algorithm X nodes : [2, 3, 6, 17, 54, 131, 412, 1373]

Figure 10.2. -queens solved as exact cover. (a) The first solution for . (b) Number of solutions for to 8, equal to the OEIS sequence A000170.
What Demonstration 2 shows. No abs(r1 - r2) == abs(c1 - c2) check is written: the secondary diagonal sets D1_{r-c} and D2_{r+c} turned geometric queen attacks into pure set disjointness.
3. Compiling Partial Latin Squares for Experimental Design (reduce_latin_square_completion)¶
In industrial Taguchi / ANOVA experimental design and multi-wavelength optical switching, an Latin Square assigns each treatment once per row and once per column. How do we compile a partially filled table into Exact Cover? Every assignment (r, c) = v simultaneously satisfies three primary obligations out of total columns:
cell(r, c): cell receives exactly one symbol ( columns).row(r, v): row contains symbol exactly once ( columns).col(c, v): column contains symbol exactly once ( columns).
Pre-filled experimental clues restrict cell to emit 1 row instead of rows.
heading("Demonstration 3: Completing 6x6 partial experimental-design Latin squares")
partial_6x6 = np.array([
[1, 0, 3, 0, 5, 0],
[0, 3, 0, 5, 0, 1],
[3, 0, 5, 0, 1, 0],
[0, 5, 0, 1, 0, 3],
[5, 0, 1, 0, 3, 0],
[0, 1, 0, 3, 0, 5],
], dtype=int)
lat_res = reductions_constraints.reduce_latin_square_completion(partial_6x6, max_solutions=200)
assert lat_res["solution_count"] == 144 # Two independent 3x3 Latin squares on {2, 4, 6}: 12^2 = 144
g0 = lat_res["completed_grids"][0]
# Verify every pre-assigned clue is preserved and every row & column is a permutation of {1..6}:
mask_clue = partial_6x6 > 0
assert np.array_equal(g0[mask_clue], partial_6x6[mask_clue])
for idx in range(6):
assert sorted(g0[idx, :].tolist()) == [1, 2, 3, 4, 5, 6]
assert sorted(g0[:, idx].tolist()) == [1, 2, 3, 4, 5, 6]
print(f"6x6 partial block design solutions found : {lat_res['solution_count']} (explored only {lat_res['search_nodes']} search nodes)")
print("Completed Latin Square #1:\n", g0)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8.4, 3.7))
for ax, mat, ttl in [(ax1, partial_6x6, "Given clues (dot = open cell)"), (ax2, g0, "Completed Latin square")]:
ax.imshow(mat, cmap="Pastel1", vmin=0, vmax=6)
for r in range(6):
for c in range(6):
val_str = "." if mat[r, c] == 0 else str(mat[r, c])
ax.text(c, r, val_str, ha="center", va="center", fontsize=11, fontweight="bold")
ax.set_xticks(range(6))
ax.set_yticks(range(6))
ax.set_title(ttl)
ax.grid(False)
label_panels(fig)
plt.show()
Demonstration 3: Completing 6x6 partial experimental-design Latin squares
=========================================================================
6x6 partial block design solutions found : 144 (explored only 1150 search nodes)
Completed Latin Square #1:
[[1 2 3 4 5 6]
[2 3 4 5 6 1]
[3 4 5 6 1 2]
[4 5 6 1 2 3]
[5 6 1 2 3 4]
[6 1 2 3 4 5]]

Figure 10.3. Latin square completion. (a) The 6 × 6 partial design (dots are open cells). (b) The first of the 144 completions found by Algorithm X.
What Demonstration 3 shows. An unconstrained grid has ways to fill its 18 blank cells, yet Algorithm X finds all 144 completions, and shows that there are no others, in 1,150 search nodes. The count can be checked by hand: the blank cells form two independent Latin squares on the symbols (even rows with odd columns, odd rows with even columns), and there are Latin squares of order 3, so .
4. Why MRV Branching Reduces the Search Tree¶
What happens if we turn off Knuth’s MRV heuristic and instead branch on uncovered primary columns in arbitrary lexicographic order? If the first uncovered column has 6 candidate options while another uncovered column already has 0 options (a dead end) or 1 forced option (unit propagation), blind fixed-order branching multiplies that dead end by at every level.
heading("Demonstration 4: MRV (minimum remaining values) against fixed-column branching")
def fixed_order_exact_cover_nodes(primary_elements: list, subsets: dict[str, list], max_solutions: int = 50) -> tuple[int, int]:
"""Algorithm X WITHOUT MRV: always branches on the first uncovered primary element in list order."""
elem_to_keys = {e: set() for e in primary_elements}
sub_sets = {k: set(v) for k, v in subsets.items()}
for k, s in sub_sets.items():
for e in s:
if e in elem_to_keys:
elem_to_keys[e].add(k)
sols = [0]
nodes = [0]
def _dfs(uncov: list, active: set[str]) -> None:
if sols[0] >= max_solutions:
return
nodes[0] += 1
if not uncov:
sols[0] += 1
return
e = uncov[0] # Blind fixed choice: ignores dead ends or unit-forced columns elsewhere
cands = sorted(k for k in elem_to_keys[e] if k in active)
for k in cands:
cov = sub_sets[k]
conf = set()
for x in cov:
if x in elem_to_keys:
conf |= elem_to_keys[x]
_dfs([u for u in uncov if u not in cov], active - conf)
if sols[0] >= max_solutions:
return
_dfs(list(primary_elements), set(sub_sets.keys()))
return sols[0], nodes[0]
# Compare MRV vs. Fixed-Order across 5x5 Latin-square clue densities (putting clues in bottom rows so top cells branch blindly):
clue_benchmarks = []
base_5 = np.array([
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 3, 4, 5],
[4, 5, 1, 2, 3],
[5, 1, 2, 3, 4],
], dtype=int)
# Also test a 4x4 grid with a bottom-row contradiction (two 3s, zero 4s in row 3) where fixed-order blindly explores top rows first:
infeas_4 = np.zeros((4, 4), dtype=int)
infeas_4[3, :] = [1, 2, 3, 3] # Row 3 has no candidate for symbol 4
def build_latin_instance(grid: np.ndarray):
n = grid.shape[0]
prim = (
[f"cell({r},{c})" for r in range(n) for c in range(n)]
+ [f"row({r},{v})" for r in range(n) for v in range(1, n + 1)]
+ [f"col({c},{v})" for c in range(n) for v in range(1, n + 1)]
)
subs = {}
for r in range(n):
for c in range(n):
vs = [int(grid[r, c])] if grid[r, c] > 0 else list(range(1, n + 1))
for v in vs:
subs[f"({r},{c})={v}"] = [f"cell({r},{c})", f"row({r},{v})", f"col({c},{v})"]
return prim, subs
cases_mrv = [
("4x4, sparse clues", np.array([[0,0,0,0],[0,0,0,0],[3,4,1,2],[4,3,2,1]])),
("5x5, clues at the bottom", base_5),
("4x4, contradictory clues", infeas_4),
]
labels_b, mrv_n, fix_n = [], [], []
for name_c, g_c in cases_mrv:
pr_c, sb_c = build_latin_instance(g_c)
r_mrv = reductions_constraints.exact_cover_algorithm_x(pr_c, sb_c, max_solutions=50)
s_fix, n_fix = fixed_order_exact_cover_nodes(pr_c, sb_c, max_solutions=50)
assert r_mrv["solution_count"] == s_fix
labels_b.append(name_c)
mrv_n.append(r_mrv["search_nodes"])
fix_n.append(n_fix)
print(f"{name_c:25s}: Solutions = {s_fix:2d} | MRV Nodes = {r_mrv['search_nodes']:4d} vs. Fixed-Column Nodes = {n_fix:6d} ({n_fix / r_mrv['search_nodes']:6.1f}x speedup)")
assert fix_n[1] > 10 * mrv_n[1]
assert mrv_n[2] <= 5 and fix_n[2] > 3000 # MRV unit-propagates forced clues and aborts in 4 nodes vs. 3,593
x_pos = np.arange(len(labels_b))
fig, ax = plt.subplots(figsize=(7.4, 4.0))
ax.bar(x_pos - 0.18, fix_n, width=0.35, color="#C0392B", label="Fixed-column ordering (no MRV)")
ax.bar(x_pos + 0.18, mrv_n, width=0.35, color="#2166AC", label="Knuth Algorithm X (MRV S-heuristic)")
ax.set_yscale("log")
ax.set_xticks(x_pos)
ax.set_xticklabels(labels_b)
ax.set_ylabel("Search tree nodes visited (log scale)")
ax.set_title("Search nodes with and without MRV branching")
ax.legend(fontsize=8.5)
plt.show()
Demonstration 4: MRV (minimum remaining values) against fixed-column branching
==============================================================================
4x4, sparse clues : Solutions = 4 | MRV Nodes = 33 vs. Fixed-Column Nodes = 1033 ( 31.3x speedup)
5x5, clues at the bottom : Solutions = 2 | MRV Nodes = 36 vs. Fixed-Column Nodes = 95984 (2666.2x speedup)
4x4, contradictory clues : Solutions = 0 | MRV Nodes = 4 vs. Fixed-Column Nodes = 3593 ( 898.2x speedup)

Figure 10.4. Search nodes on a logarithmic scale for three Latin-square puzzles with fixed column order and with MRV branching. MRV reduces the nodes by factors of 31, 2,666 and 898; on the contradictory puzzle it needs 4 nodes.
Inside the algorithm¶
Look at 4x4, contradictory clues in Demonstration 4: fixed-order branching explores 3,593 nodes near the top of the board before it meets the contradiction at the bottom, whereas MRV takes the forced clues first and finds the column with 0 candidates after 4 nodes. This is the fail-first principle of constraint satisfaction: since every primary constraint must be satisfied eventually, take the tightest one now. We inspect exact_cover_algorithm_x and verify a clean standalone solver.
Check against the library¶
heading("Inside the algorithm: reductions_constraints.exact_cover_algorithm_x")
print(show_source(reductions_constraints.exact_cover_algorithm_x))
def naive_fixed_column_exact_cover(
primary_elements: list,
subsets: dict[str, list],
secondary_elements: list | None = None,
max_solutions: int = 100,
) -> dict:
"""Reference Generalized Exact Cover solver using lexicographic (non-MRV) primary branching."""
prim_sorted = sorted(set(primary_elements), key=str)
all_valid = set(prim_sorted) | (set() if secondary_elements is None else set(secondary_elements))
sub_sets = {k: set(v) for k, v in subsets.items()}
elem_to_keys = {e: set() for e in all_valid}
for k, s in sub_sets.items():
for e in s:
elem_to_keys[e].add(k)
solutions: list[list[str]] = []
nodes = [0]
def _solve(uncov_prim: set, active_keys: set[str], chosen: list[str]) -> None:
if len(solutions) >= max_solutions:
return
nodes[0] += 1
if not uncov_prim:
solutions.append(list(chosen))
return
# Pick lexicographically first uncovered primary element (NO MRV):
e_pick = min(uncov_prim, key=str)
cands = sorted(k for k in elem_to_keys[e_pick] if k in active_keys)
for k in cands:
cov = sub_sets[k]
conf = set()
for e in cov:
conf |= elem_to_keys[e]
chosen.append(k)
_solve(uncov_prim - cov, active_keys - conf, chosen)
chosen.pop()
_solve(set(prim_sorted), set(sub_sets.keys()), [])
return {"solutions": solutions, "solution_count": len(solutions), "search_nodes": nodes[0]}
# Verify exact solution-set equivalence on N-Queens (N = 6) while comparing search nodes:
prim6 = [f"R{r}" for r in range(6)] + [f"C{c}" for c in range(6)]
sec6 = [f"D1_{d}" for d in range(-5, 6)] + [f"D2_{s}" for s in range(11)]
subs6 = {f"Q({r},{c})": [f"R{r}", f"C{c}", f"D1_{r-c}", f"D2_{r+c}"] for r in range(6) for c in range(6)}
mrv_q6 = reductions_constraints.exact_cover_algorithm_x(prim6, subs6, secondary_elements=sec6, max_solutions=100)
lex_q6 = naive_fixed_column_exact_cover(prim6, subs6, secondary_elements=sec6, max_solutions=100)
set_mrv = {tuple(sorted(s)) for s in mrv_q6["solutions"]}
set_lex = {tuple(sorted(s)) for s in lex_q6["solutions"]}
assert set_mrv == set_lex and len(set_mrv) == 4
assert mrv_q6["search_nodes"] < lex_q6["search_nodes"]
print(f"6-Queens exact solution parity verified (4 solutions): MRV = {mrv_q6['search_nodes']} nodes vs. Lexicographic = {lex_q6['search_nodes']} nodes")
Inside the algorithm: reductions_constraints.exact_cover_algorithm_x
====================================================================
def exact_cover_algorithm_x(
primary_elements: list,
subsets: dict[str, list],
secondary_elements: list | None = None,
max_solutions: int = 100,
) -> dict:
"""Solve generalized Exact Cover via Knuth's Algorithm X with Minimum-Remaining-Values (MRV) column branching."""
if max_solutions < 1:
raise ValueError("max_solutions must be >= 1.")
prim_set = set(primary_elements)
sec_set = set() if secondary_elements is None else set(secondary_elements)
if prim_set & sec_set:
raise ValueError("primary_elements and secondary_elements must be disjoint.")
all_valid = prim_set | sec_set
sub_sets: dict[str, set] = {}
elem_to_keys: dict = {e: set() for e in all_valid}
for k, items in subsets.items():
s_items = set(items)
if not s_items.issubset(all_valid):
raise ValueError(f"Subset {k!r} contains elements outside primary | secondary universe.")
sub_sets[k] = s_items
for e in s_items:
elem_to_keys[e].add(k)
solutions: list[list[str]] = []
nodes = [0]
def _search(uncovered_prim: set, active_keys: set[str], chosen: list[str]) -> None:
if len(solutions) >= max_solutions:
return
nodes[0] += 1
if not uncovered_prim:
solutions.append(list(chosen))
return
# Knuth S-heuristic (MRV): pick uncovered primary element with fewest active covering subsets:
best_e = None
best_cands: list[str] | None = None
for e in sorted(uncovered_prim, key=str):
cands = [k for k in elem_to_keys[e] if k in active_keys]
if not cands:
return
if best_cands is None or len(cands) < len(best_cands):
best_e = e
best_cands = cands
if len(best_cands) == 1:
break
assert best_e is not None and best_cands is not None
for k in sorted(best_cands):
covered_now = sub_sets[k]
# Eliminate every active subset sharing ANY primary or secondary element with covered_now:
conflict_keys: set[str] = set()
for e in covered_now:
conflict_keys |= elem_to_keys[e]
next_prim = uncovered_prim - covered_now
next_active = active_keys - conflict_keys
chosen.append(k)
_search(next_prim, next_active, chosen)
chosen.pop()
if len(solutions) >= max_solutions:
return
_search(set(prim_set), set(sub_sets.keys()), [])
return {"solutions": solutions, "solution_count": len(solutions), "search_nodes": nodes[0]}
6-Queens exact solution parity verified (4 solutions): MRV = 131 nodes vs. Lexicographic = 153 nodes
Exercises¶
Worked solutions are in 10_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Compile domino and 3-cell L-tromino tilings of boards into
exact_cover_algorithm_x. Verify (a) Kasteleyn’s exact count of36domino tilings on , (b)0domino tilings when opposite same-color corners(0,0)and(3,3)are deleted vs.>0when(0,0)and(0,3)are deleted, and (c) exact L-tromino tilability of all 16 single-defect boards.Find how it fails. Verify all
ValueErrorinput guards onexact_cover_algorithm_x,reduce_n_queens_to_exact_cover, andreduce_latin_square_completion, then demonstrate (a) why making -Queens diagonals primary constraints returns0solutions for all , and (b) how omittingcell(r,c)constraints in Latin-square reduction produces multi-symbol cell collisions.Implement it yourself. Implement
reduce_mini_sudoku_4x4(clue_grid, max_solutions=300)compiling Mini-Sudoku into 64 primary columns (16 cell + 16 row + 16 col + 16 box) and solving viaexact_cover_algorithm_x. Verify: (i) an empty grid has exactly288valid Sudoku completions, (ii) a 6-clue puzzle has two completions and becomes unique (solution_count == 1) when a seventh clue is added, and (iii) a box-conflict grid yields0solutions.
heading("Self-check for the exercises")
assert sorted(res_knuth["solutions"][0]) == ["B", "D", "F"]
assert counts_nq == [1, 0, 0, 2, 10, 4, 40, 92]
assert lat_res["solution_count"] == 144
assert mrv_n[2] <= 5 and fix_n[2] > 3000
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.