Backtracking
Backtracking
Difficult Problems
• Partition
– Partition n positive integers s1, s2, s3, …, sn into
two groups A and B such that the sum of the
numbers in each group is the same.
– [9, 4, 6, 3, 5, 1,8]
– A = [9, 4, 5] and B = [6, 3, 1, 8]
• Subset Sum Problem
– Does any subset of n positive integers s1, s2, s3,
…, sn have a sum exactly equal to c?
– [9, 4, 6, 3, 5, 1,8] and c = 18
– A = [9, 4, 5]
n-Queens Problem
A queen that is placed on an n x n chessboard, may
attack with any other queen placed in the same
column, row, or diagonal.
8x8 Chessboard
Can n queens be placed on an n x n chessboard
so that no queen attacks another queen?
4x4
8x8
Difficult Problems
• Many difficult problems require you to find
either a subset or permutation that satisfies
some constraints and (possibly also)
optimizes some objective function.
• These may be solved by organizing the
solution space into a tree and systematically
searching this tree for the answer.
Solution Space
• Solution Space is a set that includes at least one
solution to the problem.
• Subset problem.
n = 2, {00, 01, 10, 11}
n = 3, {000, 001, 010, 100, 011, 101, 110, 111}
• Solution space for subset problem has 2n
members.
• Non systematic search of the space for the answer
takes O(2n) time.
Solution Space
• Permutation problem.
n = 2, {12, 21}
n = 3, {123, 132, 213, 231, 312, 321}
• Solution space for a permutation problem has n!
members.
• Non systematic search of the space for the answer
takes O(n!) time.
Backtracking and Branch and Bound
• Backtracking and branch and bound perform a
systematic search and take much less time than the
time taken by a non systematic search.
Tree Organization Of Solution Space
• Set up a tree structure such that the paths from root to
leaves represent members of the solution space.
• For a size n subset problem, this tree structure has 2n
leaves.
• For a size n permutation problem, this tree structure has
n! leaves.
• The tree structure is too big to store in memory; it also
takes much time to create the tree structure.
• Portions of the tree structure are created by the
backtracking and branch and bound algorithms as
needed.
Subset Tree For n = 4
( fixed – sized tuple )
x1=1 x1= 0
x3=1 x3 = 0
x4=1 x4=0
x1=1 x1 = 3
x1=2
x2 = 2 x2 = 3 x2 = 1 x2 = 3 x2 = 1 x2 = 2
x1=1 x1= 0
x1=1 x1= 0
x1=1 x1= 0
x1=1 x1= 0
x1=1 x1= 0
2 34 50
18
x 2= 2 3 1 3 1 2 4 1 2 3
4 4
3 8 13 19 24 29 35 40 45 51 56 61
x3=
3 4 2 4 2 3 3 4 1 4 1 3 2 4 1 4 1 2 2 3 1 3 1 2
4 6 9 11 14 16 20 22 25 27 30 32 36 38 41 43 46 48 52 54 57 59 62 64
x4=
4 3 4 2 3 2 4 3 4 1 3 1 4 2 4 1 2 1 3 2 3 1 2 1
5 7 10 12 15 17 21 23 26 28 31 33 37 39 42 44 47 9 53 55 58 60 63 65
Tree organization of the 4-queens solution space. Nodes are numbered as in depth
first search.
1
x1=1 x1=2
2
18
3 8 13 29
19 24
B x3=1
B B
9 11 14 16 30
B B B
x4=3
15 31
B
Portion of the tree that is generated during backtracking( n=4 ).
n - queens problem algorithm
• Every element on the same diagonal that
runs from the upper left to the lower right
has the same row – column value.
i – j = k – l or i + j = k + l
First equation implies
j–l=i–k
Second equation implies
j–l=k–i
• Therefore, two queens lie on the same diagonal if
and only if j – l = i – k
Algorithm place( k, l )
// It returns true if a queen can be placed in column i
// It tests both whether i is distinct from all previous values
// x [ 1 ], ….x [ k-1 ] and there is other queen on the same
//diagonal.
// Abs(r) returns the absolute value of r.
{
for j = 1 to k-1 do // for all previous queens
{ // Two in the same column or in the same diagonal
if ( ( x [ j ] = l ) or ( Abs( x[ j ] - l ) = Abs( j - k ) ) ) then
return false;
}
return true ;
}
Algorithm NQueen(k,n)
//Using backtracking, this procedure prints all
//possible placements of n queens on an n×n
//chessboard so that they are nonattacking.
{
for l =1 to n do // check place of column for queen k
{
if place( k, l ) then
{
x[ k ] = l;
if( k = n )then write( x[1:n] );
else NQueens( k+1, n);
}
}
}
Sum of subsets
• Given n distinct positive numbers wi, and m,
find all subsets that sum to m.
• We can formulate this problem using
either
– Fixed- or variable – sized tuples.
Variable- sized tuple
• Ex:- n=4, ( w1, w2, w3, w4 )= ( 11,13, 24, 7 ), m=31.
– Solutions are ( 11, 13, 7 ) and ( 24, 7 )
• Rather than representing the solution by wi ’s, we can
represent by giving the indices of these wi
• Now the solutions are ( 1, 2, 4 ) and ( 3, 4 ).
• Different solutions may have different-sized tuples.
• We use the following condition to avoid generating
multiple instances of the same subset ( e.g., ( 1,2,4) and
(1,4,2) )
– xi < xi+1
Subset Tree for n=4 (variable- sized tuple )
1
x1=1 x1=4
x1=2
x1=3
3 4 5
2
x3=1 x3 = 0
x4=1 x4=0
and
nw )
The initial call is SumOfSub( 0, 1, ∑ i=1 i
Algorithm SumOfSub( s, k, r )
// Find all subsets of w[ 1:n ] that sum to m
n
// It is assumed that w[1] ≤ m and ∑ wi ≥ m
i=1
// The values of x[j] 1<=j<k, have already been determined.
K-1 n
// s= ∑ w[j]*x[j] and r= ∑ w[j] . W[j]’s in increasing order.
j=1 j=k
{
x[ k ]=1; // left child
if( s + w[k] = m ) then write( x[ 1: k ] ) ; // Subset found
else if ( s + w [ k ] + w[ k+1 ] ≤ m )
then SumOfSub( s+ w[k], k+1, r- w[k] )
// Generate right child and evaluate B k
...
x1=1 2 3
3 1 3 1 3
x2 =1 2 2 2
X3 =1
2 3
A 4-node graph and all possible 3-colorings
1 2
4 3
x1= 1 2 3
X2= 2 3 1 3 1 2
X3= 1 3 1 2 2 3 1 2 2 3 1 3
X4= 2 3 2 2 3 3 1 3 1 3 1 3 1 1 2 2 1 2
Algorithm :- finding all m- colorings of a graph.
Function mColoring is begun by first assiging the graph to its adjacency
matrix, setting the array x[ ] to zero, and then invoking the statement
mColoring( 1 );
Algorithm mColoring( k )
// k is the index of the next vertex to color.
{
repeat
{ // Generate all legal assignments for x[k]
{
repeat
{
x[k] = ( x[k] +1) mod ( m+1 ); // Next highest color.
if ( x[k]=0 ) then return; // All colors have been used.
for j = 1 to n do
{
if (( G[ k,j ] ≠ 0 ) and ( x[k] = x[j] )) then
break;
}
if( j = n+1 ) then return; // Color found
} until ( false );
}
Hamiltonian cycles:-
A Hamiltonian cycle is a round-trip path along n edges of
connected undirected graph G that visits every vertex once and
returns to its starting position.
1 2 3 4
8 7 6 5
1,2,8,7,6,5,4,3,1
1 2 3
5 4
Solution Space :-
All paths from the root to solution states
define the solution space of the problem.
Ex :- 1
X1=1
X1=4
X1=2 X1=3
2 34 50
18
x 2= 2 3 1 3 1 2 4 1 2 3
4 4
3 8 13 19 24 29 35 40 45 51 56 61
x3=
3 4 2 4 2 3 3 4 1 4 1 3 2 4 1 4 1 2 2 3 1 3 1 2
4 6 9 11 14 16 20 22 25 27 30 32 36 38 41 43 46 48 52 54 57 59 62 64
x4=
4 3 4 2 3 2 4 3 4 1 3 1 4 2 4 1 2 1 3 2 3 1 2 1
5 7 10 12 15 17 21 23 26 28 31 33 37 39 42 44 47 9 53 55 58 60 63 65
Tree organization of the 4-queens solution space. Nodes are numbered as in depth
first search.
Problem state :-
Each node in the tree is a problem
state.
Ex:- 1 2 18
and so on
Solution States :-
These are those problem states
S for which the path from the root to S
define a tuple in the solution space.
Ex:-
5 7 10 12 15 17 21 and so on
General Backtracking Algorithms :-
Assume all answer nodes are to be found.
Let T(x1,x2,…..xi) be the set of all possible paths for xi+1 such that
(x1,x2,…….., xi+1) is also a path to a problem state.
x1=1 x1= 0
4 14 1 1 2 3 4
13 2 3 12 5 6 7 8
6 11 5 10 9 10 11 12
9 8 7 15 13 14 15
Branch And Bound
FIFO branch and bound finds solution closest to root.
Backtracking may never find a solution because tree
depth is infinite (unless repeating configurations are
eliminated).
• Least-cost branch and bound directs the search to
parts of the space most likely to contain the
answer. So it could perform better than
backtracking.