Backtracking Part-1 (Nqueen)
Backtracking Part-1 (Nqueen)
• N-Queen
• Graph coloring
• Sudoko
• Hamiltonian Graph
• Sum of subsets
• 0/1 Knapsack
• Travelling Salesman Problem
Backtracking
e) f) g) h)
i)
j)
Basic Steps
NQueens(k, n) { Place(k, i)
for (i=1 to n ) {
{
for (j=1 to k-1) {
if Place(k, i) {
if ((x[j]=i) or (Abs(x[j]-i)=Abs(j-k)))
x[k]=i
//same column or same diagonal
If(k=n) then write (x[1:n]);
return false;
else Nqueens(k+1,n);
}
}
} return true;
} }
Backtracking – Eight Queens Problem
Try for different n values!
• N=1 1 solution
• N=2 No solution
• N=3 No solution
• N=4 2 solutions (2, 4, 1, 3 and 3, 1, 4, 2)
• N=5 1, 3, 5, 2, 4 and possibly more solutions
• N=6 2, 4, 6, 1, 3, 5 and possibly more solutions
Time and Space complexity
• In the given algorithm, the main program calls the function Nqueens(k,
n) which calls the function Place(k, i). The function Place(k, i) checks
the already placed queens. So it has O(N-n) worst case running time.
Since O(N-n)<O(N), we can write O(N-n)=O(N)
Since the function Nqueens iterates n times and for each iteration it
calls the function Place(k, i) function the total time complexity would
be O(N^2).
• Besides, Nqueens(k, n) is a recursive function. Thus, the recursive call
of T(n-1) will run n times because it will run only for the safe cells.
Since we have started by filling up the rows, there won't be more than n
(number of queens left) safe cells in the row in any case. Which in turn
results in nT(n-1) times. By adding the results above we get T(n)= nT(n-1) +
O(N^2)
Recursion Tree method