Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

10. Problem reduction: exact cover with Algorithm X

School of Engineering, Nazarbayev University

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 NN-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

  1. Formulate Exact Cover (Ax=1,  x∈{0,1}M\mathbf{A}\mathbf{x} = \mathbf{1},\; \mathbf{x} \in \{0,1\}^M) and execute Knuth’s Algorithm X (reductions_constraints.exact_cover_algorithm_x) on canonical set-partitioning benchmarks.

  2. Distinguish primary (‘covered exactly once’) from secondary (‘covered at most once’) constraints in Generalized Exact Cover (reduce_n_queens_to_exact_cover).

  3. Compile multi-rule combinatorial designs such as N×NN\times N Latin squares (reduce_latin_square_completion) and Sudoku into pure 0-1 incidence matrices without modifying a line of the solver.

  4. 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

1. Exact Cover & Knuth’s Algorithm X: One Engine for Exact Partitioning

Given a finite universe of primary elements UP\mathcal{U}_P and a collection of candidate subsets {Sk⊆UP}k=1M\{S_k \subseteq \mathcal{U}_P\}_{k=1}^M, the Exact Cover Problem asks for a subcollection of subsets that partitions UP\mathcal{U}_P—covering every primary element once and only once. Stacking subsets as rows of a binary matrix A∈{0,1}M×∣UP∣\mathbf{A} \in \{0, 1\}^{M \times |\mathcal{U}_P|}, we seek x∈{0,1}M\mathbf{x} \in \{0, 1\}^M such that:

A⊤x=1∣UP∣(every primary column has column sum 1)(1.1)\mathbf{A}^\top \mathbf{x} = \mathbf{1}_{|\mathcal{U}_P|} \qquad \text{(every primary column has column sum } 1\text{)} \tag{1.1}

Knuth’s Algorithm X solves Equation (1.1) recursively:

  1. If UP=∅\mathcal{U}_P = \emptyset, record the current subset selection as an exact cover.

  2. MRV Branching (S-heuristic): Pick an uncovered primary column e∗∈UPe^* \in \mathcal{U}_P covered by the fewest remaining active rows (if 0 rows cover e∗e^*, backtrack immediately).

  3. For each candidate row kk covering e∗e^*, include kk, delete all columns in SkS_k and every competing row sharing any element with SkS_k, and recurse.


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 size 748x396 with 1 Axes>

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 NN-Queens (reduce_n_queens_to_exact_cover)

How do you place NN non-attacking queens on an N×NN \times N board without writing a custom chessboard solver? Look at the constraints on placing a queen at (r,c)(r, c):

  • Primary constraints (2N2N columns, covered exactly once): Every row R0..R{N-1} must hold a queen, and every column C0..C{N-1} must hold a queen.

  • Secondary constraints (4N−24N - 2 diagonals, covered at most once): Each (r−c)(r - c) diagonal and (r+c)(r + c) anti-diagonal can hold 0 or 1 queen—many diagonals remain empty (2N−1>N2N - 1 > N).

Row Q(r,c)  =  {Rr,  Cc⏟primary (exact 1),  Dr−c+,  Dr+c−⏟secondary (≤1)}(2.1)\text{Row } Q(r, c) \;=\; \big\{\underbrace{R_r,\; C_c}_{\text{primary (exact 1)}},\; \underbrace{D^+_{r-c},\; D^-_{r+c}}_{\text{secondary }(\leq 1)}\big\} \tag{2.1}

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 size 990x418 with 2 Axes>

Figure 10.2. NN-queens solved as exact cover. (a) The first solution for N=8N = 8. (b) Number of solutions for N=1N = 1 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 N×NN \times N Latin Square assigns each treatment v∈{1,…,N}v \in \{1,\dots,N\} once per row and once per column. How do we compile a partially filled N×NN \times N table into Exact Cover? Every assignment (r, c) = v simultaneously satisfies three primary obligations out of 3N23N^2 total columns:

  1. cell(r, c): cell (r,c)(r, c) receives exactly one symbol (N2N^2 columns).

  2. row(r, v): row rr contains symbol vv exactly once (N2N^2 columns).

  3. col(c, v): column cc contains symbol vv exactly once (N2N^2 columns).

Pre-filled experimental clues restrict cell (r,c)(r, c) to emit 1 row instead of NN rows.


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 size 924x407 with 2 Axes>

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 6×66 \times 6 grid has 618≈1.0×10146^{18} \approx 1.0 \times 10^{14} 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 3×33 \times 3 Latin squares on the symbols {2,4,6}\{2, 4, 6\} (even rows with odd columns, odd rows with even columns), and there are 3!⋅2!=123! \cdot 2! = 12 Latin squares of order 3, so 122=14412^2 = 144.


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 6×6\times at every level.


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 size 814x440 with 1 Axes>

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


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.

  1. Verify a result. Compile 1×21\times 2 domino and 3-cell L-tromino tilings of 4×44\times 4 boards into exact_cover_algorithm_x. Verify (a) Kasteleyn’s exact count of 36 domino tilings on 4×44\times 4, (b) 0 domino tilings when opposite same-color corners (0,0) and (3,3) are deleted vs. >0 when (0,0) and (0,3) are deleted, and (c) exact L-tromino tilability of all 16 single-defect 4×44\times 4 boards.

  2. Find how it fails. Verify all ValueError input guards on exact_cover_algorithm_x, reduce_n_queens_to_exact_cover, and reduce_latin_square_completion, then demonstrate (a) why making NN-Queens diagonals primary constraints returns 0 solutions for all N≥2N \geq 2, and (b) how omitting cell(r,c) constraints in Latin-square reduction produces multi-symbol cell collisions.

  3. Implement it yourself. Implement reduce_mini_sudoku_4x4(clue_grid, max_solutions=300) compiling 4×44\times 4 Mini-Sudoku into 64 primary columns (16 cell + 16 row + 16 col + 16 box) and solving via exact_cover_algorithm_x. Verify: (i) an empty 4×44\times 4 grid has exactly 288 valid 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 yields 0 solutions.


Self-check for the exercises
============================
All checks passed.