Unit IV
Unit IV
UNIT IV
BACKTRACKING
Introduction - NXN Queen's Problem - Sum of Subsets - Graph Coloring - Hamiltonian's Circuit -
Travelling Salesman Problem - Generating Permutation.
INTRODUCTION
Backtracking
1. Many problems which deal with searching for a set of solutions or for an optimal solution
satisfying some constraints can be solved using the backtracking formulation.
2. To apply backtracking method, the desired solution must be expressible as an n-tuple (x1…xn)
where xi is chosen from some finite set Si.
3. The problem is to find a vector, which maximizes or minimizes a criterion function P(x1….xn).
4. The major advantage of this method is, once we know that a partial vector (x1,…xi) will not lead
to an optimal solution that (mi+1………..mn) possible test vectors may be ignored entirely.
5. Many problems solved using backtracking require that all the solutions satisfy a complex set of
constraints.
6. These constraints are classified as: i) Explicit constraints. ii) Implicit constraints.
1) Explicit constraints:
Explicit constraints are rules that restrict each Xi to take values only from a given set. Some examples are,
!" ≥ 0 or Si = {all non-negative real nos.}
All tuples that satisfy the explicit constraint define a possible solution space for I.
2) Implicit constraints:
The implicit constraint determines which of the tuples in the solution space I can actually satisfy the
criterion functions.
Recursion is the key in backtracking programming. As the name suggests we backtrack to find the solution.
We start with one possible move out of many available moves and try to solve the problem if we are able
to solve the problem with the selected move then we will print the solution else we will backtrack and
select some other move and try to solve it. If none if the moves work out, we will claim that there is no
solution for the problem.
Generalized Algorithm:
Consider n by n chess board, and the problem of placing n queens on the board without the queens
threatening one another.
The solution space is {1, 2, 3, , n}n. The backtracking algorithm may record the columns where the different
queens are positioned. Trying all vectors (p1, ..., pn) implies 56 cases. Noticing that all the queens must
reside in different columns reduces the number of cases to n!.
The 4 queen problem is a case of more general set of problems namely “n queen problem”. The basic idea:
How to place n queen on n by n board, so that they don’t attack each other. As we can expect the complexity
of solving the problem increases with n. We will briefly introduce solution by backtracking. The board
should be regarded as a set of constraints and the solution is simply satisfying all constraints.
For example: Q1 attacks some positions, therefore Q2 has to comply with these constraints and take place,
not directly attacked by Q1. Placing Q3 is harder, since we have to satisfy constraints of Q1 and Q2. Going
the same way, we may reach point, where the constraints make the placement of the next queen impossible.
Therefore, we need to relax the constraints and find new solution. To do this we are going backwards and
finding new admissible solution.
To keep everything in order we keep the simple rule: last placed, first displaced. In other words, if we place
successfully queen on the ith column but cannot find solution for (i+1) th queen, then going backwards we
will try to find other admissible solution for the ith queen first. This process is called backtracking.
Algorithm: -
Note the positions which Q1 is attacking. So the next queen Q2 has to options: B3 or B4. We choose the first
one B3.
Again with red we show the prohibited positions. It turned out that we cannot place the third queen on the
third column (we have to have a queen for each column!). In other words, we imposed a set of constraints
in a way that we no longer can satisfy them in order to find a solution. Hence we need to revise the
constraints or rearrange the board up to the state which we were stuck. Now we may ask a question what
we have to change. Since the problem happened after placing Q2 we are trying first with this queen. We
know that there were to possible places for Q2. B3 gives problem for the third queen, so there is only one
position left – B4:
As we can see from the new set of constraints (the red positions) now we have admissible position for Q3,
but it will make impossible to place Q4 since the only place is D3. Hence placing Q2 on the only one left
position B4 didn’t help. Therefore, the one step backtrack was not enough. We need to go for second
backtrack. Why? The reason is that there is no position for Q2, which will satisfy any position for Q4 or Q3.
Hence we need to deal with the position of Q1. We have started from Q1 so we will continue upward and
placing the queen at A2.
Now it is easy to see that Q2 goes to B4, Q3 goes to C1 and Q4 takes D3:
To find this solution we had to perform two backtracks. In order to find all solutions, we use as you can
guess – backtrack!
Start again in reverse order we try to place Q4 somewhere up, which is not possible. We backtrack to Q3
and try to find admissible place different from C1. Again we need to backtrack. Q2 has no other choice and
finally we reach Q1. We place Q1 on A3:
Continuing further we will reach the solution on the right. Is this distinct solution? No it is rotated first
solution. In fact, for 4x4 board there is only one unique solution. Placing Q1 on A4 has the same effect as
placing it on A1. Hence we explored all solutions.
Backtracking Algorithm
The idea is to place queens one by one in different columns, starting from the leftmost column. When we
place a queen in a column, we check for clashes with already placed queens. In the current column, if we
find a row for which there is no clash, we mark this row and column as part of the solution. If we do not
find such a row due to clashes, then we backtrack and return false.
a. If the queen can be placed safely in this row then mark this [row, column] as part of the
solution and recursively check if placing queen here leads to a solution.
c. If placing queen doesn't lead to a solution then unmark this [row, column] (Backtrack) and go
to step (a) to try other rows.
4. If all rows have been tried and nothing worked, return false to trigger backtracking.
Algorithm:
//return true if a queen can be placed in k th row and I th column. otherwise it returns //
//false .X[] is a global array whose first k-1 values have been set. Abs® returns the //absolute value of r.
Return true;
For I=1 to n do
X [k]=I;
Else nquenns(k+1,n) ;
Solution:
• The solution vector X (X1…Xn) represents a solution in which Xi is the column of the th row where
Ith queen is placed.
• Second, we have to check no two queens are in same column. The function, which is used to check
these two conditions, is [I, X (j)], which gives position of the Ith queen, where I represents the row
and X (j) represents the column position.
• Consider two dimensional array A[1: n,1:n] in which we observe that every element on the same
diagonal that runs from upper left to lower right has the same value.
• Also, every element on the same diagonal that runs from lower right to upper left has same value.
• Suppose two queens are in same position (i,j) and (k,l) then two queens lie on the same diagonal ,
if and only if |j-l|=|I-k|.
• Initialize x array to zero and start by placing the first queen in k=1 in the first row.
• To find the column position start from value 1 to n, where ‘n’ is the no. Of columns or no. Of queens.
• If k=1 then x (k)=1.so (k,x(k)) will give the position of the k th queen. Here we have to check whether
there is any queen in the same column or diagonal.
• For this considers the previous position, which had already, been found out. Check whether
X(I)=X(k) for column |X(i)-X(k)|=(I-k) for the same diagonal.
• If any one of the conditions is true then return false indicating that k th queen can’t be placed in
position X (k).
• For not possible condition increment X (k) value by one and precede d until the position is found.
• If the position X (k) n and k=n then the solution is generated completely.
• If k<n, then increment the ‘k’ value and find position of the next queen.
• If the position X (k)>n then k th queen cannot be placed as the size of the matrix is ‘N*N’.
• So decrements the ‘k’ value by one i.e. we have to back track and after the position of the previous
queen.
SUM OF SUBSETS
Subset sum problem is to find subset of elements that are selected from a given set whose sum adds up to
a given number K. We are considering the set contains non-negative values. It is assumed that the input set
is unique (no duplicates are presented).
One way to find subsets that sum to K is to consider all possible subsets. A power set contains all those
subsets generated from a given set. The size of such a power set is 2N.
Using exhaustive search we consider all subsets irrespective of whether they satisfy given constraints or
not. Backtracking can be used to make a systematic consideration of the elements to be selected.
Assume given set of 4 elements, say w[1] … w[4]. Tree diagrams can be used to design backtracking
algorithms. The following tree diagram depicts approach of generating variable sized tuple.
In the above tree, a node represents function call and a branch represents candidate element. The root
node contains 4 children. In other words, root considers every element of the set as different branch. The
next level sub-trees correspond to the subset that includes the parent node. The branches at each level
represent tuple element to be considered. For example, if we are at level 1, tuple_vector [1] can take any
value of four branches generated. If we are at level 2 of left most node, tuple_vector [2] can take any value
of three branches generated, and so on…
For example the left most child of root generates all those subsets that include w[1]. Similarly the second
child of root generates all those subsets that includes w[2] and excludes w[1].
As we go down along depth of tree we add elements so far, and if the added sum is satisfying explicit
constraints, we will continue to generate child nodes further. Whenever the constraints are not met, we
stop further generation of sub-trees of that node, and backtrack to previous node to explore the nodes not
yet explored. In many scenarios, it saves considerable amount of processing time.
The tree should trigger a clue to implement the backtracking algorithm. It prints all those subsets whose
sum adds up to given number. We need to explore the nodes along the breadth and depth of the tree.
Generating nodes along breadth is controlled by loop and nodes along the depth are generated using
recursion (post order traversal).
Pseudo code
else
generate the nodes of present level along breadth of tree and recur for next levels
GRAPH COLORING
For the graph-coloring problem we are interested in assigning colors to the vertices of an undirected graph
with the restriction that no two adjacent vertices are assigned the same color. The optimization version
calls for coloring a graph using the minimum number of colors. The decision version, known as k-coloring,
asks whether a graph is colorable using at most k colors.
The 3-coloring problem is a special case of the k-coloring problem where k=3 (i.e., we are allowed to use at
most 3 colors). The 3-coloring problem is known to be NP-complete, which means that there is no known
polynomial time algorithm to solve it. Using backtracking will not provide an efficient algorithm either but
it serves as a good example to illustrate the technique.
Backtracking is a systematic way to search through the solution space to a problem. In backtracking we
begin by defining a solution space for the problem. This space must include at least one (optimal) solution
to the problem. Normally, the solution is viewed as a sequence of stages with some decisions that are to be
made at each stage. In the case of the maze traversal problem, we may define the solution space to consist
of all paths from the entrance to the exit, which are then generated by depth-first or breadth-first search.
The resulting search tree is appropriately named state-space (search) tree or backtracking search tree.
Example
Consider a graph and the corresponding backtracking search tree that results when applying backtracking
to solve the 3-coloring problem for the given graph
• When we reach the lowest level and try to color vertex e, we find that it is not possible to color it
any of the three colors; therefore, we backtrack to the previous level and try the next choice for the
coloring of vertex d.
• We see that the coloring of vertex d with color 2 leads to a violation (d and b are adjacent and have
same color).
• We continue to d=3 and then down to e=1, which gives the solution, {a=1,b=2,c=3,d=3,e=1}.
The three types of movements to build and explore the search tree:
• Move across a level to try the different choices for the coloring of a particular vertex.
• Move down from the current tree level to the level below.
• Move up from current tree level to the level above. This is backtracking.
HAMILTONIAN'S CIRCUIT
HAMILTONIAN CYCLES:
• Let G=(V,E) be a connected graph with „n‟ vertices. A HAMILTONIAN CYCLE is a round trip path
along „n‟ edges of G which every vertex once and returns to its starting position.
• If the Hamiltonian cycle begins at some vertex V1 belongs to G and the vertex are visited in the
order of V1,V2…….Vn+1,then the edges are in E,1<=I<=n and the Vi are distinct except V1 and Vn+1
which are equal. Consider an example graph G1.
• The backtracking algorithm helps to find Hamiltonian cycle for any type of graph.
1. Define a solution vector X(Xi……..Xn) where Xi represents the I th visited vertex of the proposed cycle.
3. The solution array initialized to all zeroes except X(1)=1,because the cycle should start at vertex 1.
5. The vertex from 1 to n are included in the cycle one by one by checking 2 conditions,
6. When these two conditions are satisfied the current vertex is included in the cycle, else the next vertex
is tried.
7. When the nth vertex is visited we have to check, is there any path from nth vertex to first 8 vertex. if no
path, the go back one step and after the previous visited node.
Loop
If (x (k)=0) then
return;
If k=n then
Print (x)
Else
Hamiltonian (k+1);
End if
Repeat
Repeat
E'( F = 1 G' 8 − 1 >' "A (! [F] = ! [8]) then break; // Check for distinction.
@A ((8 < 5) '( ((8 = 5) 15> B [! [5], ! [1]] ≠ 0)) then return;
Until (false);
• pizza delivery
• mail delivery
• traveling salesman
• garbage pickup
• bus service/ limousine service
• reading gas meters
The traveling salesman problem consists of a salesman and a set of cities. The salesman has to visit each
one of the cities starting from a certain one (e.g. the hometown) and returning to the same city. The
challenge of the problem is that the traveling salesman wants to minimize the total length of the trip.
The traveling salesman problem can be described as follows:
TSP = {(G, f, t): G = (V, E) a complete graph, f is a function V×V → Z, t ∈ Z, G is a graph that contains a
traveling salesman tour with cost that does not
if smallest cost from current city to unvisited city results would result in a tour cost greater than best found
so far. No need to consider any more tours from this city.
Let A be an array of n cities and let 1 l n be a parameter. Let lengthSoFar be the length of the path A[1], A[2],
. . . , A[l] and let minCost > 0 be another parameter. We want to compute min(minCost, L), where L is the
minimum length of a tour visiting all cities in A[1..n] under the condition that the tour starts by visiting the
cities from A[1..l] in the given order.
2. if l = n
4. else for i ← l + 1 to n
In line 7, we check if the beginning of the tour is already longer than the best complete tour found so far. If
this is the case, we will not look for tours that begin in this way, and undo the selection just made. Another
way to describe it, is that we maintain that minCost is an upper bound on the length of the best tour. This
bound is improved every time we find a better tour. Before we enter any branch of recursion, we first
compute a lower bound on the length of any solutions that could be found in that branch. This lower bound
is new Length. When the lower bound is higher than our current upper bound, we skip the branch,
otherwise we explore the branch to look for a better upper bound. Backtracking algorithms with pruning
are also called branch-and-bound algorithms.
Example
Consider the graph shown below with 4 vertices.
We will assume that the starting node is 1 and the ending node is obviously 1. Then 1, {2, … ,4}, 1 forms a
tour with some cost which should be minimum. The vertices shown as {2, 3, …. ,4} forms a permutation of
vertices which constitutes a tour. We can also start from any vertex, but the tour should end with the same
vertex.
Since, the starting vertex is 1, the tree has a root node R and the remaining nodes are numbered as depth-
first order. As per the tree, from node 1, which is the live node, we generate 3 braches node 2, 7 and 12. We
simply come down to the left most leaf node 4, which is a valid tour {1, 2, 3, 4, 1} with cost 30 + 5 + 20 + 4
= 59. Currently this is the best tour found so far and we backtrack to node 3 and to 2, because we do not
have any children from node 3. When node 2 becomes the E- node, we generate node 5 and then node 6.
This forms the tour {1, 2, 4, 3, 1} with cost 30 + 10 + 20 + 6 = 66 and is discarded, as the best tour so far is
59.
Similarly, all the paths from node 1 to every leaf node in the tree is searched in a depth first manner and
the best tour is saved. In our example, the tour costs are shown adjacent to each leaf nodes. The optimal
tour cost is therefore 25.
GENERATING PERMUTATION
Input:
Output:
[’A’, ‘B’, ‘C’] [’A’, ‘C’, ‘B’], [’B’, ‘A’, ‘C’], [’B’, ‘C’, ‘A’], [’C’, ‘A’, ‘B’], [’C’, ‘B’, ‘A’]
OR
ABC, ACB, BAC, BCA, CAB, CBA
Backtracking algorithm
1. Fix a character at the first position and the use swap to put every
character at the first position
3. Use swap to revert the string back to its original form for next
iteration.