The NQueen problem is a famous example of backtracking. After reading from the source, I have tried the below code snippet.
int isSafe(int k,int i,int *x)
{
int j;
for(j=0;j<k;j++)
{
//old queen is placed at jth row of x[j] column
//new queen to be placed at kth row of ith column
if(i==x[j] || abs(k-j)==abs(i-x[j]))
return 0;
}
return 1;
}
int Nqueen(int k, int* sol, int N)
{
int col;
if( k == N )
{
printSol(sol,N);
return 1;
}
else
{
for(col = 1;col <= N; col++) //determines appropriate column number of the kth queen to be placed
{
if( isSafe(k,col,sol) )
{
sol[k] = col;
if( Nqueen(k+1, sol, N) )
return 1;
sol[k] = 0; // backtrack
}
}
return 0; // solution not possible
}
}
I am getting the output as:
1 5 8 6 3 7 2 4
However, when i comment the statement which backtracks, I am getting the same output without any problem.
int Nqueen(int k, int* sol, int N)
{
int col;
if( k == N )
{
printSol(sol,N);
return 1;
}
else
{
for(col = 1;col <= N; col++) //determines appropriate column number of the kth queen to be placed
{
if( isSafe(k,col,sol) )
{
sol[k] = col;
if( Nqueen(k+1, sol, N) )
return 1;
// sol[k] = 0; <-------------- Notice this change
}
}
return 0;
}
}
What exactly has made NQueen problem, a backtracking one?
Isn't it a simple recursive approach?
The sol[k] = 0
is not the backtracking part. The backtracking is done in the recursive call: if( Nqueen(k+1, sol, N) )
.
The idea of backtracking is an exhaustive search - you are trying to search all possibilities, until one is found. In here, you are trying all possible assignments of queens in the board, and "keep on" if it is still safe. If you find it unsafe, you return from the recursion with a failure, and trying the next option.
I believe the commented out line only makes sure that if no solution is found, the resulting array is [0,...,0]
, and not some nonesense array.