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에 어떤 문제가 있습니까?
간단한 재귀 방식이 아닙니까?