Spring 1998
Backtracking
Backtracking is a systematic way to go through all the possible configurations of a space. These configurations may be all possible arrangements of objects or all possible ways of building a collection of them.
We must generate each oe of the possible confgurations exactly once systematically. We represent our configurations by a vector A = (a1, a2, ... , an) , where each element ai is selected from an ordered set of possible candidates Si for position i.
Algorithm:
Since each solution can be thought of as a traversal of a tree, we can use a Depth-first Traversal to yield a recursive algorithm.
Backtrack-DFS (A,k)
if A = (a1, a2, ... , ak) is a
solution, report it.
else
k = k + 1
compute Sk
while Sk not empty do
ak = an element in Sk
Sk = Sk - a k
Backtrack(a,k)
Subset Example:
To construct all 2n subsets, we set Sk = (true, false) and A is a solution whenever k >= n. Thus, each solution vector has size n and consists of a series of true or falses. We will use the number i to represent a true value for the ith position and a - to represent false.
Permutation Example:
To construct all n! permutaions, we set Sk = {1, 2, ..., n} - A and A is a solution whenever k = n + 1. Thus, each solution vector has size n and consists of a series of numbers.