NQueen problem是backtracking的着名示例。從source閱讀後,我嘗試了下面的代碼片段。NQueen真的回溯?
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
}
}
我收到output爲:
1 5 8 6 3 7 2 4
然而,當我評論這回溯的聲明,我收到相同output沒有任何問題。
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;
}
}
究竟是什麼導致了NQueen問題,一個回溯的問題?
難道不是一個簡單的遞歸方法嗎?