Algorithm X with dancing links
Also known as DLX, Dancing links
constraint constraint-search
Algorithm X solves exact cover: choose rows of a 0/1 matrix so that every primary column is covered exactly once and every secondary column at most once. At each node it picks the uncovered primary column with the fewest rows left (a column with none is a dead end), covers it, and tries each of its rows in turn, covering that row's other columns. Dancing links make covering cheap and exactly reversible: a cover unlinks nodes from doubly linked lists, and the uncover relinks them in reverse order. The links here are indices into flat arrays, so the structure needs no unsafe code, and secondary column headers link only to themselves, so search never branches on them. Use it for Sudoku, polyomino tilings and N-queens, with the diagonals as secondary columns.
Pseudocode
algorithm Algorithm-X(M)input: exact cover problem M: primary and secondary columns, rows over themoutput: each set of rows that covers every primary column once and every secondary column at most oncesearch(⟨⟩)procedure search(CHOSEN)if no primary column is uncovered thenreport(CHOSEN)returnc ← the uncovered primary column with the fewest rows ▷ the first one on a tieif size(c) = 0 thenreturn ▷ a dead endcover(c)for each row r of c, top to bottom doappend(CHOSEN, r)for each other node j of r, left to right docover(column(j))search(CHOSEN)for each other node j of r, right to left douncover(column(j))remove-last(CHOSEN)uncover(c)procedure cover(c)unlink c from the header ring ▷ a secondary header is a ring of its ownfor each row r of c, top to bottom dofor each other node j of r, left to right dounlink j from its columnsize(column(j)) ← size(column(j)) − 1procedure uncover(c)for each row r of c, bottom to top dofor each other node j of r, right to left dosize(column(j)) ← size(column(j)) + 1relink j into its columnrelink c into the header ringIn the crates
constraint-searchExact cover with primary and secondary columns, branching on the column with the fewest rows, on index-linked arrays.
Lineage
Comes from
builds on DFS
Led to
Nothing on this site.
Papers
- Dancing links Donald E. Knuth · 2000· arXiv preprint