Backtracking Algo
Backtracking Algo
1
Introduction
Contents:
• Backtracking
• N-Queen Problem
2
What is Backtracking?
3
What is Backtracking?
5
When Backtracking is used?
• Backtracking is used when there are multiple
solutions for a problem and you need all
solutions.
• It’s not used for Optimization problem.
6
Problems on Backtracking
• Problems on Backtracking Algorithm:
– N-Queen problem
– Subset Sum Problem
– Hamiltonian Circuit problem
• Depth-First Search or DFS algorithm is a recursive
algorithm that uses the backtracking principle.
7
Generalized Algorithm
Pick a starting point.
while (Problem is not solved)
For each path from the starting point.
check if selected path is safe,
if yes select it and make recursive call to rest of the
problem
If recursive calls returns true, then return true
else undo the current move and return false.
End For
If none of the move works out, return false
NO SOLUTON
8
N-Queen Problem
9
N-Queen Problem
10
N-Queen Problem
2) Move onto the next row, placing a queen on the first available
square there (that doesn't conflict with the previously placed
queens).
When you get stuck, remove the queens that got you there, until you
get to a row where there is another valid square to try.
12
N-Queen Problem
• Rules
The Queens will not be in the
– Same row
– Same column
– Same diagonal
13
4-Queen Problem
14
4-Queen Problem
15
4-Queen Problem
That’s a solution…
16
State space tree of the 4-queen problem
17
Tree organization of the 4-Queen solution space
A possible tree organization for the case n = 4. A tree such as this is called
a permutation tree. The edges are labeled by possible values of x_{i}
Edges from level 1 to level 2 nodes specify the values for x_{1} . Thus, the
leftmost subtree contains all solutions with x_{1} = 1 ; its leftmost subtree
contains all solutions with x_{1} = 1 and x_{2} = 2 and so on. Edges from
level i to level i + 1 are labeled with the values of x_{i} . The solution space
is defined by all paths from the root node to a leaf node.
18
Portion of the tree that is generated during backtracking
19
4-Queen Problem (Solution)
20
Two solutions of 4 Queen Problem
21
How many solutions for 8-Queen
Problem?
22
Thank you
23