|
ADS
Algorithms and Data Structures
|
The headers of include/ADS/backtrack realize the backtrack of chapter 16 of the book, i.e., the enumeration of the feasible solutions of a problem by a visit in depth of the tree of its partial choices, with its exercises (the subsets, the permutations, the \( n \) queens, the tour of the knight, the Sudoku and the anagrams), and beyond the book two families of search that rest on the same scheme: the exact cover of Knuth, on dancing links and on sparse sets, and the satisfiability of a formula in conjunctive normal form, by DPLL and by the learning of clauses. This page collects what the headers take for granted: the definitions and the notation (see Definitions and notation), the scheme of the enumeration with the arguments of its correctness and of its cost (see The scheme of the enumeration), and the properties on which the puzzles, the exact cover and the satisfiability rest (from Queens, tours of the knight and Sudoku to Satisfiability). The pseudocode of each algorithm is instead on the page of its header, in the comment of its function, together with the section of the book, or the paper, that it follows.
A problem of enumeration asks for all the feasible solutions of an instance, or for one of them, or for their number; a solution is a vector \( S[ 0 .. n - 1 ] \) whose item \( S[ i ] \) is taken from a set of choices \( C( S , i ) \) that depends on the items before it (section 16.2 of the book). The vectors \( S[ 0 .. i - 1 ] \) are the partial solutions, and they form a tree, the tree of the choices, whose root is the empty vector and whose node \( S[ 0 .. i - 1 ] \) has a child \( S[ 0 .. i ] \) for each choice of \( C( S , i ) \); the feasible solutions are some of its nodes, usually leaves. To prune is to leave a subtree unvisited because a test on its root proves that it holds no feasible solution.
| Symbol | Meaning |
|---|---|
| \( S[ 0 .. n - 1 ] \), \( i \) | the vector of a solution and the place being chosen, i.e., the depth in the tree of the choices |
| \( C( S , i ) \) | the choices allowed in the place \( i \) by \( S[ 0 .. i - 1 ] \) |
| \( f( S ) \), visit( S ) | the processing of a solution, which returns true to stop the enumeration |
| \( Q[ r ] \) | the column of the queen of the row \( r \) of the board |
| \( \mathit{len}( i ) \), \( \mathrm{size}( x ) \) | the options of the item of an exact cover still compatible with those chosen |
| \( \ell \), \( \lnot \ell \), \( \pm ( v + 1 ) \) | a literal, its negation, and the code of the literal of the variable \( v \) in a clause of the library, positive or negative |
The backtrack of section 16.2 is the recursive visit of the tree of the choices: at the node \( S[ 0 .. i - 1 ] \) it tries each choice \( c \in C( S , i ) \) in turn, sets \( S[ i ] \gets c \), processes \( S \) if it is a feasible solution, and goes on from \( S[ 0 .. i ] \) unless a test prunes it; when the choices of the place \( i \) are over, it goes back to the place \( i - 1 \), which is what gives the method its name. The only state is \( S \) itself, updated in place and restored on the way back, so that the space is that of the deepest path, \( O( n ) \) items, while the tree may have exponentially many nodes.
Lemma 1 (the enumeration). If every feasible solution is a node of the tree of the choices and each pruned subtree holds none, the backtrack processes each feasible solution exactly once, in the lexicographic order of the choices when \( C( S , i ) \) is scanned in increasing order.
Indeed, two nodes of the tree are distinct vectors, a visit in depth meets each node of the subtrees it enters once, and the subtrees it skips hold no solution by hypothesis. The order follows since the visit in depth of an ordered tree meets its nodes in the lexicographic order of their paths from the root. The cost is the number of nodes visited times the cost of a node, i.e., of building \( C( S , i ) \) and of the tests: for the \( k \)-subsets of subsets() in Enumeration.h, where a place is in or out, the tree has fewer than \( 2^{n+1} \) nodes, and the pruning of the nodes with \( k \) items in, or with too few items left to reach \( k \), leaves only the nodes on a path to one of the \( \binom{n}{k} \) solutions, i.e., at most \( ( n + 1 ) \binom{n}{k} \); for the permutations of permutations() the nodes of the depth \( i \) are \( n! / ( n - i )! \), and in all
\[ \sum_{i=0}^{n} \frac{n!}{( n - i )!} = n! \sum_{j=0}^{n} \frac{1}{j!} < e \, n! , \tag{1} \]
so that the work per permutation is \( O( n ) \), the cost of the scan of the items not used at each node. The derangements are the permutations pruned at the place \( i \) by the item \( i \), and the subsets of subsetSum(), whose items are positive, are pruned as soon as their sum exceeds \( k \), since no item added later can lower it.
The recursion is a convenience, not a need: the iterative backtrack of nQueensIterative() keeps the place \( k \) and the choice \( V[ k ] \) of each place, advances \( V[ k ] \) to its next feasible value, and moves \( k \) forward when one is found and backward when the values are over, i.e., the same visit with the stack of the calls replaced by the vector \( V \) itself.
The \( n \) queens are placed one per row, since two queens on a row attack each other; a solution is then the vector \( Q \) of their columns, a permutation, and the tree has at most \( e \, n! \) nodes by (1), against the \( \binom{n^2}{n} \) placements of \( n \) queens on the board. Two queens \( ( r , Q[ r ] ) \) and \( ( r' , Q[ r' ] ) \) share a diagonal if and only if \( | Q[ r ] - Q[ r' ] | = | r - r' | \), which is the test of admissible() of NQueens.h, \( O( n^2 ) \) on a whole placement. nQueens() instead keeps three sets of the columns attacked on the current row, by the columns taken and by the two families of diagonals; moving to the next row shifts the sets of the diagonals by one column, one to the left and one to the right, and the free columns of a row are the complement of their union. As masks of \( n \le 32 \) bits these are a few operations on a word, and the next free column is its lowest 1 bit, so that each node of the tree costs \( O( 1 ) \).
The tour of the knight of KnightTour.h is a Hamiltonian path in the graph of the moves of the knight, whose nodes are the \( n^2 \) squares and have degree at most 8; the backtrack extends the path by a move to a square not visited yet, and goes back from the squares with no such move. In the order of the book the tree may be explored for a very long time before a tour is found. The rule of Warnsdorff tries first the moves to the squares with the fewest onward moves, i.e., it visits first the squares that would otherwise become dead ends; it is a heuristic, with no bound on the backtracks it saves, but on the boards of practical size it finds a tour almost without going back, i.e., in time about linear in \( n^2 \).
The Sudoku of Sudoku.h fills the \( n^4 \) squares of a grid of side \( N = n^2 \) in the order of the rows, each with a number that is not on its row, its column or its block (check(), \( O( N ) \)), and the given squares are skipped. The tree has depth \( n^4 \) and at most \( N \) children per node; the cost is therefore a constant for the classic \( n = 3 \), a large one, and grows superpolynomially with \( n \), as the problem is NP-complete on grids of side \( n^2 \). The anagrams of Anagrams.h are the permutations of the multiset of the characters that split into words: choosing each distinct character once per place gives each permutation of the multiset once, and a test of the prefixes of the words prunes a branch as soon as its current word cannot be completed.
Given a set of items, some primary and some secondary, and a family of options, each a set of items, an exact cover is a set of options that contains each primary item exactly once and each secondary item at most once. Many puzzles are exact covers: the queens with the rows and the columns as primary items and the diagonals as secondary ones, the Sudoku with the 324 primary items (a square, a row with a number, a column with a number, a block with a number) and the options of the \( 9^3 \) numbers in the squares. The search (Knuth's Algorithm X) is a backtrack whose place is a primary item not covered yet and whose choices are the options that contain it and none of the items already covered: choosing an option covers its items, and removes from the problem every option that meets one of them.
Lemma 2 (the dancing links). On a circular doubly linked list with the links \( L \) and \( R \), the removal of a node \( x \) by
\[ R[ L[ x ] ] \gets R[ x ] , \quad L[ R[ x ] ] \gets L[ x ] \tag{2} \]
leaves \( L[ x ] \) and \( R[ x ] \) as they were; hence the assignments \( R[ L[ x ] ] \gets x \) and \( L[ R[ x ] ] \gets x \) put it back, provided that the removals done after that of \( x \) have been undone, in the reverse order, before.
Indeed, after the later removals are undone the neighbors of \( x \) are again \( L[ x ] \) and \( R[ x ] \), which (2) did not touch. In ExactCover of DancingLinks.h the items are a list and the nodes of each item, one per option that contains it, a vertical list; covering an item takes it off its list and the other nodes of each of its options off their vertical lists, and uncovering undoes the same steps in the reverse order, so that the links after the search are those before it (an audit of the class). Each removal and each reinsertion costs \( O( 1 ) \), and the work of a node of the tree is the number of links updated, the measure of updates(). The search branches on the primary item with the fewest options left (the MRV heuristic): an item with none ends the branch at once, and an item with one forces its option without branching, which keeps the tree small.
FastExactCover of FastExactCover.h solves the exact cover with colors (Algorithm C), where an option may give a color to a secondary item and several options may share the item if they give it the same color. The options of each item are a sparse set of Briggs and Torczon, a segment of an array whose first \( \mathrm{size}( x ) \) entries are the active options of \( x \), each node knowing its place: an option leaves the set by a swap with the last active entry and a decrement of the size, in \( O( 1 ) \). The removed entries stay in the segment, after the active ones; hence restoring a level needs no inverse swap, only the sizes of that level written back, and the sets are again those of the level, in another order. This costs \( O( a ) \) per level, \( a \) the active items, against an update per link of the dancing links, and the memory is read by consecutive indices. In both classes the worst case stays exponential, the exact cover being NP-complete.
A formula in conjunctive normal form is a set of clauses, each a disjunction of literals, i.e., of variables and of negated variables; it is satisfiable if some assignment of truth values makes every clause true (a model). A clause of a partial assignment is satisfied if one of its literals is true, conflicting if all are false, and unit if all are false but one, which is free and then must be true in every model that extends the assignment.
Lemma 3 (the unit propagation). Making true the free literal of a unit clause, until no clause is unit or one is conflicting, loses no model of the formula that extends the assignment; a conflicting clause proves that there is none.
The procedure of Davis, Putnam, Logemann and Loveland (dpll() of SatSolvers.h) alternates this propagation with a branch on a free literal, both values tried, and goes back on a conflict; by Lemma 1 and Lemma 3 it is complete, and its tree has at most \( 2^n \) leaves for \( n \) variables. Branching on a literal of a shortest open clause makes the propagation of the branch likely to produce more units.
The learning of clauses of Cdcl keeps the literals assigned in a trail, each with its level (the number of decisions before it) and its reason (the clause that forced it, none for a decision). A conflict is analyzed by resolution: the conflicting clause is resolved with the reasons of its literals of the current level, from the last assigned backwards, until a single literal of that level is left, the first unique implication point. The clause \( C \) so obtained is implied by the formula, since resolution preserves the models; it is false under the trail, and after the levels above the second largest level of its literals are canceled it is unit, so that it forces the negation of the implication point there (the jump back, possibly over several levels). The same assignment that led to the conflict can then never occur again, and the search is complete, since the number of clauses that can be learned is finite. Each clause watches two of its literals, with the invariant that a clause whose watched literals are both false is conflicting or satisfied; a literal that becomes false thus visits only the clauses that watch it, and the canceling of levels needs no update of the watches. The decisions take the free variable of largest activity, increased at each conflict for the variables met in the analysis and decayed by raising the increment (VSIDS), with the value it had last (the phase saving); the restarts cancel all the levels after a number of conflicts that follows the sequence of Luby, Sinclair and Zuckerman, \( 1 , 1 , 2 , 1 , 1 , 2 , 4 , \ldots \) times 100, which keeps the learned clauses and the activities and, for a search whose length is unknown, is within a logarithmic factor of the best strategy of restarts.