Backtracking

Get Backtracking essential facts below. View Videos or join the Backtracking discussion. Add Backtracking to your PopFlock.com topic list for future reference or share this resource on social media.
## Description of the method

### Pseudocode

### Constraint satisfaction

## See also

## Notes

## References

## Further reading

## External links

This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.

Backtracking

**Backtracking** is a general algorithm for finding all (or some) solutions to some computational problems, notably constraint satisfaction problems, that incrementally builds candidates to the solutions, and abandons a candidate ("backtracks") as soon as it determines that the candidate cannot possibly be completed to a valid solution.^{[1]}^{[2]}

The classic textbook example of the use of backtracking is the eight queens puzzle, that asks for all arrangements of eight chess queens on a standard chessboard so that no queen attacks any other. In the common backtracking approach, the partial candidates are arrangements of *k* queens in the first *k* rows of the board, all in different rows and columns. Any partial solution that contains two mutually attacking queens can be abandoned.

Backtracking can be applied only for problems which admit the concept of a "partial candidate solution" and a relatively quick test of whether it can possibly be completed to a valid solution. It is useless, for example, for locating a given value in an unordered table. When it is applicable, however, backtracking is often much faster than brute force enumeration of all complete candidates, since it can eliminate many candidates with a single test.

Backtracking is an important tool for solving constraint satisfaction problems,^{[3]} such as crosswords, verbal arithmetic, Sudoku, and many other puzzles. It is often the most convenient (if not the most efficient^{[]}) technique for parsing,^{[4]} for the knapsack problem and other combinatorial optimization problems. It is also the basis of the so-called logic programming languages such as Icon, Planner and Prolog.

Backtracking depends on user-given "black box procedures" that define the problem to be solved, the nature of the partial candidates, and how they are extended into complete candidates. It is therefore a metaheuristic rather than a specific algorithm - although, unlike many other meta-heuristics, it is guaranteed to find all solutions to a finite problem in a bounded amount of time.

The term "backtrack" was coined by American mathematician D. H. Lehmer in the 1950s.^{[5]} The pioneer string-processing language SNOBOL (1962) may have been the first to provide a built-in general backtracking facility.

The backtracking algorithm enumerates a set of *partial candidates* that, in principle, could be *completed* in various ways to give all the possible solutions to the given problem. The completion is done incrementally, by a sequence of *candidate extension steps.*

Conceptually, the partial candidates are represented as the nodes of a tree structure, the *potential search tree.* Each partial candidate is the parent of the candidates that differ from it by a single extension step; the leaves of the tree are the partial candidates that cannot be extended any further.

The backtracking algorithm traverses this search tree recursively, from the root down, in depth-first order. At each node *c*, the algorithm checks whether *c* can be completed to a valid solution. If it cannot, the whole sub-tree rooted at *c* is skipped (*pruned*). Otherwise, the algorithm (1) checks whether *c* itself is a valid solution, and if so reports it to the user; and (2) recursively enumerates all sub-trees of *c*. The two tests and the children of each node are defined by user-given procedures.

Therefore, the *actual search tree* that is traversed by the algorithm is only a part of the potential tree. The total cost of the algorithm is the number of nodes of the actual tree times the cost of obtaining and processing each node. This fact should be considered when choosing the potential search tree and implementing the pruning test.

In order to apply backtracking to a specific class of problems, one must provide the data *P* for the particular instance of the problem that is to be solved, and six procedural parameters, *root*, *reject*, *accept*, *first*, *next*, and *output*. These procedures should take the instance data *P* as a parameter and should do the following:

*root*(*P*): return the partial candidate at the root of the search tree.*reject*(*P*,*c*): return*true*only if the partial candidate*c*is not worth completing.*accept*(*P*,*c*): return*true*if*c*is a solution of*P*, and*false*otherwise.*first*(*P*,*c*): generate the first extension of candidate*c*.*next*(*P*,*s*): generate the next alternative extension of a candidate, after the extension*s*.*output*(*P*,*c*): use the solution*c*of*P*, as appropriate to the application.

The backtracking algorithm reduces the problem to the call *bt*(*root*(*P*)), where *bt* is the following recursive procedure:

procedurebt(c)isifreject(P, c)thenreturnifaccept(P, c)thenoutput(P, c) s while s ? NULLdobt(s) s## Usage considerations

The

rejectprocedure should be a boolean-valued function that returnstrueonly if it is certain that no possible extension ofcis a valid solution forP. If the procedure cannot reach a definite conclusion, it should returnfalse. An incorrecttrueresult may cause thebtprocedure to miss some valid solutions. The procedure may assume thatreject(P,t) returnedfalsefor every ancestortofcin the search tree.On the other hand, the efficiency of the backtracking algorithm depends on

rejectreturningtruefor candidates that are as close to the root as possible. Ifrejectalways returnsfalse, the algorithm will still find all solutions, but it will be equivalent to a brute-force search.The

acceptprocedure should returntrueifcis a complete and valid solution for the problem instanceP, andfalseotherwise. It may assume that the partial candidatecand all its ancestors in the tree have passed therejecttest.The general pseudo-code above does not assume that the valid solutions are always leaves of the potential search tree. In other words, it admits the possibility that a valid solution for

Pcan be further extended to yield other valid solutions.The

firstandnextprocedures are used by the backtracking algorithm to enumerate the children of a nodecof the tree, that is, the candidates that differ fromcby a single extension step. The callfirst(P,c) should yield the first child ofc, in some order; and the callnext(P,s) should return the next sibling of nodes, in that order. Both functions should return a distinctive "NULL" candidate, if the requested child does not exist.Together, the

root,first, andnextfunctions define the set of partial candidates and the potential search tree. They should be chosen so that every solution ofPoccurs somewhere in the tree, and no partial candidate occurs more than once. Moreover, they should admit an efficient and effectiverejectpredicate.## Early stopping variants

The pseudo-code above will call

outputfor all candidates that are a solution to the given instanceP. The algorithm can be modified to stop after finding the first solution, or a specified number of solutions; or after testing a specified number of partial candidates, or after spending a given amount of CPU time.## Examples

Examples where backtracking can be used to solve puzzles or problems include:

- Puzzles such as eight queens puzzle, crosswords, verbal arithmetic, Sudoku
^{[nb 1]}, and Peg Solitaire. - Combinatorial optimization problems such as parsing and the knapsack problem.
- Logic programming languages such as Icon, Planner and Prolog, which use backtracking internally to generate answers.

The following is an example where backtracking is used for the constraint satisfaction problem:

The general constraint satisfaction problem consists in finding a list of integers , each in some range }, that satisfies some arbitrary constraint (boolean function) *F*.

For this class of problems, the instance data *P* would be the integers *m* and *n*, and the predicate *F*. In a typical backtracking solution to this problem, one could define a partial candidate as a list of integers , for any *k* between 0 and *n*, that are to be assigned to the first *k* variables . The root candidate would then be the empty list . The *first* and *next* procedures would then be

functionfirst(P, c)isk if k = nthenreturnNULLelsereturn(c[1], c[2], ..., c[k], 1)

functionnext(P, s)isk if s[k] = mthenreturnNULLelsereturn(s[1], s[2], ..., s[k - 1], 1 + s[k])

Here *length*(*c*) is the number of elements in the list *c*.

The call *reject*(*P*, *c*) should return *true* if the constraint *F* cannot be satisfied by any list of *n* integers that begins with the *k* elements of *c*. For backtracking to be effective, there must be a way to detect this situation, at least for some candidates *c*, without enumerating all those *m*^{n - k}*n*-tuples.

For example, if *F* is the conjunction of several boolean predicates, , and each *F*[*i*] depends only on a small subset of the variables , then the *reject* procedure could simply check the terms *F*[*i*] that depend only on variables , and return *true* if any of those terms returns *false*. In fact, *reject* needs only check those terms that do depend on *x*[*k*], since the terms that depend only on will have been tested further up in the search tree.

Assuming that *reject* is implemented as above, then *accept*(*P*, *c*) needs only check whether *c* is complete, that is, whether it has *n* elements.

It is generally better to order the list of variables so that it begins with the most critical ones (i.e. the ones with fewest value options, or which have a greater impact on subsequent choices).

One could also allow the *next* function to choose which variable should be assigned when extending a partial candidate, based on the values of the variables already assigned by it. Further improvements can be obtained by the technique of constraint propagation.

In addition to retaining minimal recovery values used in backing up, backtracking implementations commonly keep a variable trail, to record value change history. An efficient implementation will avoid creating a variable trail entry between two successive changes when there is no choice point, as the backtracking will erase all of the changes as a single operation.

An alternative to the variable trail is to keep a timestamp of when the last change was made to the variable. The timestamp is compared to the timestamp of a choice point. If the choice point has an associated time later than that of the variable, it is unnecessary to revert the variable when the choice point is backtracked, as it was changed before the choice point occurred.

- Ariadne's thread (logic)
- Backjumping
- Backward chaining
- Enumeration algorithm
- Sudoku solving algorithms

**^**Donald E. Knuth (1968).*The Art of Computer Programming*. Addison-Wesley.**^**Gurari, Eitan (1999). "CIS 680: DATA STRUCTURES: Chapter 19: Backtracking Algorithms". Archived from the original on 17 March 2007.**^**A. Biere; M. Heule; H. van Maaren (29 January 2009).*Handbook of Satisfiability*. IOS Press. ISBN 978-1-60750-376-7.**^**Des Watson (22 March 2017).*A Practical Approach to Compiler Construction*. Springer. ISBN 978-3-319-52789-5.**^**Rossi, Francesca; Beek, Peter Van; Walsh, Toby (August 2006). "Constraint Satisfaction: An Emerging Paradigm".*Handbook of Constraint Programming*. Foundations of Artificial Intelligence. Amsterdam: Elsevier. p. 14. ISBN 978-0-444-52726-4. Retrieved .Bitner and Reingold credit Lehmer with first using the term 'backtrack' in the 1950s.

- Gilles Brassard, Paul Bratley (1995).
*Fundamentals of Algorithmics*. Prentice-Hall.

- HBmeyer.de, Interactive animation of a backtracking algorithm
- Solving Combinatorial Problems with STL and Backtracking, Article and C++ source code for a generic implementation of backtracking

This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.

Popular Products

Music Scenes

Popular Artists