Backtracking
Backtracking
i- j = k - ·l or . i + j =k l
j-l=i-k
'
The second implies
j-l=k-i
· Therefore two queens lie on the same diagonal if and only i~ Ii - ll. Ii - kl.
Place(k i) (Algorithm 7.4) returns a boolean -value that 1s true 1f the kth
ueen can be placed in column i. It tests both whether i is distinct from all
irevious values x[l], ... , x[k- 11 an~ whether there is no other queen on the
same diagonal Its computing time 1s O(k - 1). / . b
Using Pia~ we can refine the general backtracking 1method as give~h Y
Algorithm 7.1 ~d give a precise solution to the n-queel)s' problem (Alz~n )·m
7.5). The array x[ ) is global. The algorithm is invo1¢d by NQueens , n ,.
I,; :ZS
CHAPTER 7. BACKTRACKING 7.2. Tl
374
At tl
brute fo:
place 8 I
1 Algorithm Place(k, i) allowing
2 / / Returns true if a queen can be placed in kth row and
the exar
3 / / ith column. Otherwise it returns false. x[ ] is a .
We c
4 / / global array whose first (k - 1) yalues have been set.
. erated b
5 // Abs(r) returns the absolute value of r. do hold .
6 { .
to the fl
.7 for j := 1, to k - 1 do level of 1
8 if ((x[j]=;= _i) //,Two in the sam_e column 8 x 8 chi
9 or (Abs(x[j] - i) Abs(j:.... k))) - As rE
10 . / / or iD; -the same diagonal random!:
11 .
then return, \false;
. could le!
12 return true; ' - beneath
13 } value thf
of these J
space tre
Algorithm 7.4 Can a new queen be placed?
So thee~
total nun
1 Algorithm NQueens(k, n) for ·more
2 // Using backtracking, this procedure prints all
3 / / possible placements of n queens on an n x n
4 {/ chessboard so that they are nonattacking. EXER
5
6 for i := 1 to do 1. Alg<
7 { . tion
8 if Place(k, i) then whi<
9 { .
(Alg
10 x[k] := i; · . .
11 if (k = n) then write {f[l: n]); 2. For
12 else NQueens(k + 1, n);· refle
13 solu1
} }
14 Obs1
15 } set 1
(a)
(b)
Algorithm 7.~ All solutions to then-queens problem
l
7.3. SUM OF SUBSETS
377
1
-
I
-
2 2
3 3
4 4
k n
L WiXi + L Wi 2: m
· i=l i=k+l
k n
.
Bk(xi, ... , Xk) = true iff
·
L
i=l
WiXi + .L Wi > m
, i=k+l
k
and E
i=l
WiXi + Wk+l < m
.
(7.1)
Since our algorithm will not make u_se of ,Bn, we need .not be conce~ned by
the appearance of Wn+l in this function. Although w~ haye ~ow speci~ed all
that is needed to directly use either of the backtrackmg schemas, a simpler
algorithm results if we tailor either of th~~e ~chem~o the problem at hand.
This simplification results from the realization that if Xk = 1, then
.k n
L WiXi + L Wi >m
i = 1 i=k+l
I -
_ . SUM OF SUBSETS 379
73
1
Algorithm SumOfSub(s, k, r) .
// Find all subsets of w[l : n] that sum tom. The values of x[j],
2
// 1 :=:; j < k, have already been determined. s = EJ:f
wlf] * x[j]
3
// and r = °EJ=k w[j]. The w[j]'s are i~ non?ecreasing order.
4
// It is assumed that w[l] < m and Ei=l w[i] > m.
5
6 {
// Generate left-child. Note: s + w[k] < m since Bk-1 is true.
7
8 x[k] := 1; ,
if (s + w[k] = m) then write (x[l, : k]); //_Subset foun~
9
/ / There is no recursive call here as w[J] > 0, 1 :::; J < n.
10
11 else if (s + w[k] + w[k + 1] :::; m)
12 then Su,mOfSub(s + w[k], k + 1, r - w[k]);
13 // Generate right child and evaluate Bk.
14 if ((s + r - w[k] 2: m) and (s + w[k + 1] < m)) then
15 {
16 x[k] := O;
17 SumOfSub(s,-k~ l, r - w[k]);
·:~~
18 }
19 }
EXERCISES
1. Prove that the size of the set of all subsets of n elements is 2n.
2. Let w = {5, 7, 10, 12, 15, 18, 20} and,1m = 35. Find all possible subsets
of w that sum to m. Do this using SumOfSub. Draw the portion of
the state space tree that is generated.
~· 3. With m = 35, run SumOfSub on the data (a) w = {5, 7, 10-, 12, 15, 18, 20},
(b) w = {20,18_,15,1~,10,!,5}, and_(c) w = {15,7,20,5,18,10,12} .
Are there any d1scermble differences m the computing times?
12,4,46
10.~,33 12,5,33
15,5,33 B
x 5 =1 x 5=1
d
7.4. GRAPH COLORING
- 381
I •
way that no two edges cross each other. A famous special case of the m-
colorability decision problem is the 4-color problem for planar graphs. This
problem asks the following question: given any map, can the ·regions be
colored in such a .way that no two adjacent regions have the same . color
yet only four colors are .needed? This .turns out to be a problem for which
graphs are very useful, because a map can easily.be transformed into a graph.
Each region of the map : becomes .a node, and if two regions are adjacent,
then the corresponding nodes ·are joined .by an edge. Figure 7.12 shows a
map with five regions and its corresponding ·graph. This map requires four
colors. For many years it was known that five colors were sufficient to color
any map,· but no ·map that required more than four colors .had ever been
found. After several hundred years, ·this problem .was solved by a group of
mathematicians "'ith the help of a computer. They sho.wed that in fact four
colors are sufficient. In this section .we consider not only graphs that are
produced from maps but all graphs. We are interested in determining all
the different ways in which a given graph can be colored using at most m
colors. .. . . .
. Suppo~e we represent a graph by its adjacency matrix G[l : n, l : n],
where G[i, j) . 1 if (i, j~ is an edge of G, and G[i, j] = Ootherwise .. The colors
are represented by·the mtegers 1, 2, ... , m and the solutions are given by ~he
n-tuple (x1,·, .. ,xn), where Xi is the color of node i. Using the recursive
?acktracking formulation as given in Algorithm 7.1, the resulting algori~hm
18 mColoring (Algorithm 7. 7). The underlying state space tree use~ 1s a
tree of degree m and height n + 1. .Each node at level i has m children
corresponding_ to them poosible assignments to Xi, 1 .~ ·i :::; n. Nodes at
level n + 1 are leaf nodes .. Figure 7.13 shows the state spac~ tree when n =
CHAPTERl BACKTRACKING
382
-
4 5
-
2
I
3
3 and m = 3. -- h · ad.
Function mColoring is begun by first assigning ~he ~ap to its Ja-
cency matrix, setting the array x[] to zero, and then mvoking the statement
mColoring{l);. ; · · ·
Notice the similarity between this algorithm and the general form of the
recursive backtracking schema of Algorithm 7.1. Function NextValue (Algo-
rithm 7.8) produces .the possible colors for Xk after x1 through Xk-I have
· been·defined. The main loop of mColoring repeatedly picks an element from
the set of possibilities, assigns it to xk, and then calls mColoring recursively.
For instance, Figure 7.14 shows a simple graph containing four nodes. Below
that" is the tree.that is generated by mColoring;·~Each path to a leaf repre-
sents a coloring using at most three colors. Not~ that only 12 solutions exist
__ · : w:ith exactly three colors. In this tree, after choosing x 1 = 2 and x 2 = 1,
-· : the.possible choices for xa--{U'e 2 and 3. After choosing x = 2; x = 1, and
1 2
x"a .:__2, possible values for X4 are 1 and 3. And so on.
An upper bound on the computing time of mColoring can be arrived at by
noticing ~hat the number of intern~ nodes in the state space tree is E~cf mi.
At each mternal no?e, O(mn) time is spent by NextValue to determine the
children1 co~respondmg
1
to ~egal col~rings. Hence the total time is bounded
.by Li=o m'+ n = E~1 m'n = n(mn+l - 2)/(m - 1) = O(nmn).
'
EXERCISE --
. .
1. Program ~d run mColoring (Algorithn). 7.7) using as data the complete
graphs of size n = 2, 3, 4, 5,- 6, and 7. Let the desired number of colors
be k = n and k = n/2. Tabulate the computing times for each value
7.4_ GRAPH COLORING 383
1 Algorithm mColoring(k) .
2 //This algorithm was ~ormed using the recursive backtracking
3 / / schema. The graph 1s represented by its boolean adjacency
4 // matrix G[l : n, 1 : nJ:. All assignments of 1, 2, ... , m. to the
5 / / vertices of the graph such that adjacent vertices are
6 / / assigned distinct integers are printed. k is the index
7 / / of the next vertex to color. .
8 {
-9 repeat
10 {/ / Generate all legal 'assignments for x[k].
11 NextValue(k); // Assign to x[k] a legal color.
12 if (x[k] = 0) then return; // No new color possible
13 if (k = n) then // ·At most m colors have been
14 / / used to color the n vertices.
15 write (.'.r[l : n]);
16 else mColoring(k + 1);
17 } until (false}; f'
18 }
of n and k.
CHAPTER 7. BACKTRACKING
384
1
2
3
Algorithm NextValue(k)
/ I x[l], ... , x[k - 1] have been ::~!~t
. ed integer values in
vertices have distinct
/ I the range [1, m] such tha\: determined in the range .
4 _ I I integers. A value for xJk] xt highest numbered color
5 I I [O, m]. x[k] is_ ~sign~d_. the. ne. from the adjacent vertices
6 I I while maintammg distmcfness ·sts then x[k] is 0.
7 I I of vertex k. If no such co or exi '
8 {
9 repeat
10
11 { • . d ~m + 1)· // Next highest color.
12 · ~[k] -(x[k)]
1f (x.=[ k1= 0 +th~)enmoturn·
re ' // All colors have been. used.
13 for j := 1 ton do .'
14 { ·I I Check if this color IS
15 II distinct from adjacent colors.
16 . . if ((G[k,j] f= 0) and -(x[k] . x[j]))
17 I I If (k,j) is and edge and If adJ.
18 , I I vertices have the sa~e color·
19 then break; .
20
21. ·· if (j = n + 1) then return; // New color _found
} - • - • • - • - - • . . . C. . • -
'
Algorithm 7.8 Generating a next color
- 385
The backtracking sol':1-tion vector (x1, ... , Xn) is defined so that xi rep-
resei_i~ ~he ith visited vertex of the proposed cycle. Now all we need do is
d~ne how to compute the set of possible vertices for xk if x 1, ... ,xk-I
have hlready been chosen. If k = 1, then x1 can be any of then vertices. To
avoid printing the same cycle n times, we require that-x 1 = 1. If 1 < k < n,
then ~le can be any vertex·v that is distinct from x1,x2, ... ,xk-I and vis
~nnected by an edge to Xk-l· The vertex Xn can only be the one remaining
vertex and it must be connected to both Xn...:.1 and x1, We begin by present-
ing function NextValue(k) (Algorithm 7.9), which determines a possible next
vert~ for the proposed cycle. . .
Using NextValue we can particularize the recursive backtracking schema
to find ~l Hamiltonian cycles (Algorithm 7.10). This algorith~ is started
by .first initializing the adjacency matrix G[l : n, 1 : n], then settmg x[2 : n]
to zero and x[l) to 1, and then executing Hamiltonian(2). ·
Recall from Section 5.9 the traveling salesperson problem which asked
for a tour that has minimum cost. This tour 'is a Hamiltonian cycle. For the
simple case of a graph all of whose edge costs, are identical, Hamiltonian will
CHAPTER 7. BACKTRACKING
386
Gl:
G2:
1 Algorithm NextValue(k) ·
2 I I x[l : _k - l] is a path of k - 1 distinct vertices. If x[k] = 0, then
3 I I no vertex has as yet been assigned to x[k]. After execution,
4 I I x[k] is assigned to the next highest numbered vertex which
5 I I does not already appear in x[l : k -1] and is connected by
6 I I an edge to x[k - l]. Otherwise x[k] = 0. If k = n, then ·
7 I I in addition x[k] is connected to x[l].
8 {
9 repeat
10 {
11 x[k] := (x[k] + 1) mod (n + l); I I Next vertex.
12 if (x[k] _.:. 0) then return; .. ·
13 if (G[x[k - l], x[k]] # 0) then
14 { I I Is there an edge?
15 for j _ :, 1 to k -::· l do if (x[j] = x[k]) then break;
16 I J Check for distinctness.
17 if (j .. k) then I/ If i;_!ue, then the ver~ex is .distiµct.
18 ,if. ((k < ,) or ((k ·= n) and G[x[n], x[l]] # 0))
19 · · then return;
20 }
21 } until (false);
22 }
find _a minimu~-cost_ tour if a tour exists. If the common edge cost is c, the
cost of a tour 1s en smce there are n edges in a Hamiltonian cycle.
EXERCISES
1. Determine the order of magnitude of the _worst-case computing time
for the backtracking procedure that finds all Hamiltonian cycles.
2. Draw the portion of the state space tree generated by Algorithm 7.10
for the graph Gl of Figure 7.15.
3. Generalize Hamiltonian so that it processes a g~aph whose edges have
costs associated with them and finds a Hamiltonian cycle with mini-
mum cost. You can assume that all edge costs are positiv(?.