Chapter 5 - Backtracking PDF
Chapter 5 - Backtracking PDF
Chapter 5 `
`
Set: n2 possible positions
Criterion: no two queens can threaten each other
Backtracking ` Depth-first search of a tree (preorder tree traversal)
2 Algorithms ([email protected])
` Check whether two queens threaten ` Checking the entire state space tree (number of nodes
each other: checked)
` col(i) – col(k) = i – k
` col(i) – col(k) = k - i
` w1 = 2, w2 = 4, w3 = 5
void sum_of_subsets
sum of subsets (index i,i int weight,
weight int total){
if (promising (i))
` The first call to the function
if (weight == W) sum_of_subsets(0, 0, total) where
coutt << include
i l d [1] through
h h include
i l d [i][i];
n
total = ∑ w[ j ]
else{
include [i + 1] = "yes";
sum_of_subsets
f b ( + 1,
(i 1 weight
h + w[i [ + 1],
1] totall - w[i
[ + 1]);
1]) j =1
include [i + 1] = "no";
sum_of_subsets (i + 1, weight, total - w [i + 1]); ` The number of nodes checked
} 1 + 2 + 22 + … + 2n = 2n+1
}
Algorithm 5.5
5 5 (3) The Hamiltonian Circuits Problem
` The top level call to m_coloring ` The traveling sales person problem
` m_coloring(0) ` Chapter 3: Dynamic programming
` The number of nodes in the state space tree for this ` T(n) = (n-1)(n-2)2n-3
algorithm ` Hamiltonian Circuit (also called a tour)
` Given a connected, undirected graph
` A path that starts at a given vertex, visits each vertex in the
graph exactly once, and ends at the starting vertex
Algorithm 5.6
5 6 (1) Algorithm 5.6
5 6 (2)
void
id hamiltonian
h ilt i (index (i d i) { bool promising (index i) {
index j;
index j; bool switch;
if (p
(promisingg (i))
( )) if (i == nn-1
1 && !W[vindex[n - 1]] [vindex [0]])
if (i == n-1) switch = false;
cout << vindex [0] through vindex [n - 1]; else if (i > 0 && !W[vindex[i - 1]] [vindex [i]])
switch = false;
else
l else{
for (j = 2; j <=n; j++){ switch = true;
vindex [[i + 1]] = j; j = 1;
while (j < i && switch){
hamiltonian (i + 1); if (vindex[i] == vindex [j])
} switch = false; j++;
} }
}
return switch;
}