Backtracking
Backtracking
Backtracking
Can be applied for the problems which search for a set of solutions or ask for
By
an optimal solution satisfying some constrains (conditions).
Strategy:
1) At each time one component xi is used to test the modified bounding
function Pi(x1, x2, …, xi). If it satisfies the criteria, xi is included.
2) If it is realized that the partial vector (x1, x2, …, xi) in no way lead to an
optimal solution, then backtrack operation is performed.
Solution type 1:
Or (1, 2, 4) and (3, 4) using indices of wi’s.
Solution type 2: n-tuple (x1, x2, …, xn) such that
xi {0,1} , 1≤ i ≤ n.
Then xi =0 if wi is not chosen and xi = 1 if wi is chosen.
Hence we have solutions (1, 1, 0, 1) and (0, 0, 1, 1)
Note:
Solution type 1 is called variable sized tuple solution
Solution type 2 is called variable sized tuple solution
Constraints:
i) No two tuples are same, e.g. (1, 2, 4) and (1, 4, 2)
n
ii) i1wi m
Fig. 2: Using fixed sized tuple solution: Solution space is defined by all paths from
root to any leaf node
Note: Nodes are numbered according to BFS order in both the cases. Once the tree
is built solutions can obtained by systematically search the tree.
Terminologies:
Solution states: Are those problem states for which the path from the root to S
defines a tuple in the solution space-any node in Fig. 1 and every leaf node in Fig. 2
Answer states: Are those solution states S for which the path from the root to S
defines a tuple that is member of the set of solutions of the problem.
Backtrack Solution:
Task: Generated tree after backtracking to obtain the set of solutions.
n-queens Problem
To place n queens in an n×n chessboard such that no two attack, i.e., no two
queens will be placed
i) on the same row
ii) on the same column or
iii) on the same diagonal.
Solution representations:
(x1, x2, …, xn) where xi is the column on which queen i is placed.
Observation 1: Every element on the same diagonal from the upper left to the
lower right has the same "row - column" value.
Observation 2: Every element on the same diagonal from the upper right to the
lower left has the same "row + column" value.
Now, suppose two queens are placed at positions (i, j) and (k, l).
or i + j = k + l => j – l = k - i
m-Colouring:
Chromatic number:
Planner Graph:
4-colour problem of a planner graph: Coloring of a map (A famous special case)
Important Note:
Note: We are interested for all possible solutions of m-colouring of a planer graph
Solution representation: For a graph with n nodes and m colours.
Then n-tuple solution: (x1, x2, …, xn) where xi is the colour of node i.
Height:
Time Complexity:
Problem Statement:
Tuple Solution: (x1, x2.. , xn) where xi represents the ith visited vertex of the cycle.
Fig. 2. Finding all Hamiltonian cycles
1 2
4 3
Task 2: Draw the state space tree and also draw the portion of the same generated
by m-colouring backtrack algorithm as given in Fig. 2 for the following graph.
1 2
4 3