Exact Cover & Dancing Links
Knuth’s Algorithm X for sudoku, pentominoes and n-queens.
Sudoku, the n-queens puzzle and packing the 12 pentominoes into a box look like three different puzzles. Knuth showed that they are one problem, exact cover, and solved all of them with one short backtracking algorithm. Its secret is a linked-list trick: a node removed from a doubly linked list still remembers the way back in.
What you’ll learn
- Define exact cover with primary and secondary columns, and encode sudoku (729 rows, 324 columns), n-queens and polyomino tilings as exact cover.
- State Knuth's Algorithm X, prove that it reports every exact cover exactly once, and explain why branching on a column with the fewest 1s pays off.
- Implement cover and uncover with dancing links, and explain why removals undone in reverse order restore the lists exactly, in per link.
- Place exact cover among NP-complete problems, and describe its generalizations (colors, multiplicities) and successors (decision diagrams, dancing cells).
One problem behind many puzzles
| Row | A | B | C | D | E | F | G |
|---|---|---|---|---|---|---|---|
| 1 | 0 | 0 | 1 | 0 | 1 | 1 | 0 |
| 2 | 1 | 0 | 0 | 1 | 0 | 0 | 1 |
| 3 | 0 | 1 | 1 | 0 | 0 | 1 | 0 |
| 4 | 1 | 0 | 0 | 1 | 0 | 0 | 0 |
| 5 | 0 | 1 | 0 | 0 | 0 | 0 | 1 |
| 6 | 0 | 0 | 0 | 1 | 1 | 0 | 1 |
Think first Which rows of the matrix above form an exact cover? Start from column A: only rows 2 and 4 contain it.
Rows 1, 4 and 5: covers each column once. It is the only cover. Choosing row 2 for column A rules out rows 4, 5 and 6 (they share D or G). Only rows 1 and 3 remain, the only ones containing E and B respectively, and they clash on C.
To encode a puzzle, make one column per constraint "this must happen exactly once" and one row per possible move, with a 1 wherever the move satisfies the constraint. Choosing moves becomes choosing rows.
| Puzzle | Columns (constraints) | Rows (moves) | 1s per row |
|---|---|---|---|
| sudoku | 324: each cell filled, and each digit once in each row, column and box () | 729: digit in cell | 4 |
| queens | primary (each rank, each file) and secondary (the diagonals in both directions) | : a queen on square | 4 |
| 12 pentominoes in a box | 72: each piece used, each of the 60 cells covered | 2,056: every position and orientation of every piece | 6 |
A sudoku uses digits 1–4 and four boxes. How many rows does its exact-cover matrix have?
Show the answer
64
One row per (cell, digit) pair: . There are also 64 columns: 16 for the cells and 16 each for (row, digit), (column, digit) and (box, digit). A given clue simply keeps only its own row for that cell.
Algorithm X
Every column must be covered by some row, so a natural search picks a column and branches on the rows that could cover it. Knuth calls this backtracking procedure Algorithm X:
ALGORITHM-X(A): # A: the remaining matrix
if A has no primary columns:
report the rows chosen so far; return
choose a primary column c # deterministic: fewest 1s
for each row r with A[r][c] = 1: # branch on every row that covers c
choose r
for each column j with A[r][j] = 1:
delete every row i with A[i][j] = 1 # it would cover j twice
delete column j
ALGORITHM-X(A)
restore the rows and columns deleted for r, in reverse orderDeleting a column records that it is covered; deleting the clashing rows keeps every later choice compatible with .
Let be the set of exact covers of , and for a row let be the matrix after choosing : its columns deleted, with every row that meets them. A set completes exactly when its rows avoid 's columns and cover every other primary column once (and every other secondary column at most once), that is,
Every cover contains exactly one row with a 1 in the chosen column . So the covers split into disjoint classes by that row, one class per branch:
Each has fewer primary columns, so by induction its branch reports each of its covers once; prefixed by , these are exactly the covers of that use . A primary column with no 1s gives an empty sum: the branch is a dead end, discovered at once.
The choice of column cannot change the answer, only the tree. Choosing a column with the fewest 1s, a rule Knuth credits to Golomb and Baumert (1965), is fail-first once more: a column with one 1 is a forced move that costs no branching, and a column with none kills the branch immediately. Knuth measured it. On one case of Dana Scott's 1958 pentomino puzzle the search fell from 103,005 nodes to 10,421, and on the box, with the X piece confined to one quarter to remove symmetric copies, from 28,320,810 nodes to 902,631.
def algorithm_x(X, Y, primary, partial):
"""X: column -> set of rows that cover it; Y: row -> list of its columns.
Yields every exact cover: each primary column once, each other column at most once."""
live = [c for c in X if c in primary]
if not live:
yield list(partial)
return
c = min(live, key=lambda col: len(X[col])) # the column with the fewest rows
for r in list(X[c]): # branch: which row covers column c?
partial.append(r)
removed = select(X, Y, r)
yield from algorithm_x(X, Y, primary, partial)
deselect(X, Y, r, removed)
partial.pop()
def select(X, Y, r):
removed = []
for j in Y[r]:
for i in X[j]: # every row that shares column j with r...
for k in Y[i]:
if k != j:
X[k].remove(i) # ...disappears from its other columns
removed.append(X.pop(j)) # column j is covered
return removed
def deselect(X, Y, r, removed):
for j in reversed(Y[r]): # undo in exactly the reverse order
X[j] = removed.pop()
for i in X[j]:
for k in Y[i]:
if k != j:
X[k].add(i)
Y = {1: 'CEF', 2: 'ADG', 3: 'BCF', 4: 'AD', 5: 'BG', 6: 'DEG'}
X = {c: {r for r in Y if c in Y[r]} for c in 'ABCDEFG'}
print(list(algorithm_x(X, Y, set('ABCDEFG'), []))) # [[4, 1, 5]]Dictionaries of sets stand in for the linked lists. Secondary columns are never chosen for branching, yet choosing a row still deletes every row that clashes with it there. With ranks and files as primary columns and diagonals as secondary ones, the same function counts the 92 solutions of 8 queens.
Dancing links
Algorithm X spends its time deleting rows and columns and putting them back. In Knuth's implementation, DLX, every 1 of the matrix is a node in two circular doubly linked lists, one along its row and one along its column, and every column has a header that records how many rows it still has. Taking a node out of a doubly linked list, and putting it back, are two pointer assignments each:
#include <vector>
// Node 0 is the root; nodes 1..m are column headers; every 1 of the matrix is one more node.
std::vector<int> L, R, U, D; // circular links: left, right, up, down
std::vector<int> C, S; // C[x]: the column of node x; S[c]: how many rows column c still has
long long solutions = 0;
void cover(int c) { // remove column c and every row that meets it
L[R[c]] = L[c]; R[L[c]] = R[c]; // unlink c from the list of columns
for (int i = D[c]; i != c; i = D[i]) // each row i of column c, top to bottom
for (int j = R[i]; j != i; j = R[j]) {
U[D[j]] = U[j]; D[U[j]] = D[j]; // unlink node j from its column
--S[C[j]];
}
}
void uncover(int c) { // exactly the reverse order
for (int i = U[c]; i != c; i = U[i]) // bottom to top
for (int j = L[i]; j != i; j = L[j]) {
++S[C[j]];
U[D[j]] = j; D[U[j]] = j; // j still remembers its old neighbors
}
L[R[c]] = c; R[L[c]] = c;
}
void search() {
if (R[0] == 0) { ++solutions; return; } // no primary column left: an exact cover
int c = R[0];
for (int j = R[0]; j != 0; j = R[j])
if (S[j] < S[c]) c = j; // the column with the fewest 1s
cover(c);
for (int r = D[c]; r != c; r = D[r]) { // try each row that covers c
for (int j = R[r]; j != r; j = R[j]) cover(C[j]);
search();
for (int j = L[r]; j != r; j = L[j]) uncover(C[j]);
}
uncover(c);
}Each pointer change is , so a search node costs the number of links it touches, which Knuth counts as updates. With a routine that builds the lists (secondary columns are simply left out of the header list), these functions count the 92 solutions of 8 queens, solve sudokus, and find all 9,356 tilings of the box by the 12 pentominoes, 2,339 up to the box's four symmetries, in seconds.
Why not copy the matrix at every node instead? A copy costs time proportional to the whole matrix at every step, while dancing links pays only for the links that actually change, and the search never holds more than one matrix. The same discipline, undo in reverse, is what makes the un-choose step of every backtracking program correct.
To try a row, DLX covers its other columns in the order 3, 7, 2. In which order must it uncover them when it backtracks?
- 3, 7, 2
- Any order: each column is restored independently
- 2, 7, 3
- 7, 3, 2
Show the answer
C. 2, 7, 3
Restores must happen in exactly the reverse order of removals. Covering column 7 may unlink nodes whose neighbors were already changed by covering column 3; restoring 3 first would relink nodes next to neighbors that are still missing, and the lists would be corrupted. That is why search walks the row with L links when uncovering after walking it with R links when covering.
Colors, decision diagrams and the frontier
The model stretches further than it first appears:
- Secondary columns, as in n-queens: cover at most once.
- Colors. In exact covering with colors (XCC), a row assigns a color to each secondary item it touches, and several chosen rows may share an item if they give it the same color. Think of two crossing words in a crossword that must agree on their shared letter: the letter is the color. Volume 4B of The Art of Computer Programming shows dancing links at its best on XCC problems.
- Multiplicities. Cover an item between and times instead of exactly once.
The limits are those of any NP-complete problem. A bipartite perfect matching is an exact cover of the vertices by edges, so counting exact covers includes counting perfect matchings, the permanent, which Valiant (1979) proved #P-complete. Even completing a partially filled n-queens board is NP-complete (Gent, Jefferson & Nightingale, 2017).
Key takeaways
- Exact cover chooses rows of a 0/1 matrix so that every primary column is covered exactly once and every secondary column at most once; sudoku (729 rows, 324 columns), n-queens and pentomino tilings are instances, and the problem is NP-complete.
- Algorithm X branches on the rows of one column and reports every exact cover exactly once; choosing a column with the fewest 1s turns forced moves and dead ends into instant decisions (28,320,810 nodes down to 902,631 in Knuth's pentomino count).
- Dancing links removes with , and leaves 's own links intact, so undoing removals in reverse order restores everything in per link, with one copy of the matrix for the whole search.
- Colors and multiplicities extend the model to crosswords and more; decision diagrams (DXZ) and sparse sets (dancing cells) are its newest engines, and exact cover remains NP-complete, with time over items.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In the exact-cover encoding of a sudoku, how many columns does the matrix have, and how many 1s does each row contain?
- 729 columns, 4 ones per row
- 324 columns, 4 ones per row
- 81 columns, 1 one per row
- 324 columns, 3 ones per row
Show the answer
B. 324 columns, 4 ones per row
Four families of 81 constraints each: every cell holds a digit, and each digit appears once in each row, each column and each box, for columns. A row "digit in cell " satisfies one constraint of each family, so it has four 1s.
In the n-queens encoding, why are the diagonal columns secondary (covered at most once) rather than primary?
- Because diagonals are longer than ranks and files
- Because covering every diagonal exactly once is impossible: queens touch only of the diagonals
- Because secondary columns make Algorithm X faster
- Because a queen does not attack along diagonals
Show the answer
B. Because covering every diagonal exactly once is impossible: queens touch only of the diagonals
Each queen lies on one diagonal of each direction, so queens cover diagonals, fewer than the that exist for . The constraint is "no two queens share a diagonal", which is exactly "at most once".
Algorithm X, choosing a column with the fewest 1s, reaches a node where some primary column has no 1s left. What happens next?
- It picks that column, has no row to branch on, and backtracks immediately
- It reports the rows chosen so far as a solution
- It ignores that column and keeps covering the others
- It restarts the search with a different column order
Show the answer
A. It picks that column, has no row to branch on, and backtracks immediately
The column has the fewest 1s, namely zero, so it is chosen; the loop over its rows is empty, and the branch ends at once. A rule that picked another column first could explore a large subtree before noticing that this column can never be covered.
Dancing links restores a removed node with and . Why does this put back in the right place?
- Because the lists are kept sorted by row number
- Because removal copied onto a stack together with its neighbors
- Because 's own pointers were never changed, and removals are undone in reverse order, so its old neighbors are again adjacent to each other when it returns
- Because each node stores the index of its row and column, which determine its position
Show the answer
C. Because 's own pointers were never changed, and removals are undone in reverse order, so its old neighbors are again adjacent to each other when it returns
Removal rewires the neighbors around but leaves and pointing at them. Undoing in reverse order guarantees that, at the moment is restored, those two neighbors are linked to each other exactly as they were just after left, so the two assignments splice back between them.
Further reading
- D. E. Knuth, "Dancing links," in Millennial Perspectives in Computer Science (2000); arXiv:cs/0011047.
- D. E. Knuth, The Art of Computer Programming, Vol. 4B: Combinatorial Algorithms, Part 2 (Addison-Wesley, 2022), §7.2.2.1, "Dancing links".
- R. M. Karp, "Reducibility among combinatorial problems," in Complexity of Computer Computations (Plenum, 1972), 85–103.
- M. Nishino, N. Yasuda, S. Minato & M. Nagata, "Dancing with decision diagrams: A combined approach to exact cover," Proceedings of AAAI 31 (2017), 868–874.