Professional Documents
Culture Documents
Data Structure and Algorithms: Dr. D. P. Acharjya Professor, SCOPE
Data Structure and Algorithms: Dr. D. P. Acharjya Professor, SCOPE
Dr. D. P. Acharjya
Professor, SCOPE
22-Mar-17 Dr. D. P. Acharjya 1
Backtracking
Suppose you have to make a series of decisions,
among various choices, where
You dont have enough information to know what to
choose
Each decision leads to a new set of choices
Some sequence of choices (possibly more than one)
may be a solution to your problem
Backtracking is a methodical way of trying out
various sequences of decisions, until you find
one that works.
22-Mar-17 Dr. D. P. Acharjya 2
Graphical View
0 1 2 3 0 1 2 3
Level 0 Q (0, 0) 0 Q
0 1 2 3
1 Q
Level 1 Q (1, 2)
2
0 1 2 3
3
Level 2
1. for j = 1 to (k-1) do
2. {
3. if ((x[j]=i) or (Abs(x[j]-i)=Abs(j-k)))
4. then return false
5. }
6. return true
1. for i =1 to n do
2. {
3. if Place (k, i) then
4. {
5. x[k]=i
6. if (k=n) then write (x[1:n])
7. else NQueens (k+1,n)
8. }
9. }