This program for n-queens uses a weird logic for backtracking. I tried to track the code many times but i always get confused with it. I am really confused with the Place(int pos) function.
#include<stdio.h>
#include<conio.h>
int a[30],count=0;
int place(int pos)
{
int i;
for(i=1;i<pos;i++)
{
if( (a[i]==a[pos]) || ((abs(a[i]-a[pos])==abs(i-pos))) )
{
return 0;
}
}
return 1;
}
void print_sol(int n)
{
int i,j;
count++;
printf("\nSOLUTION #%d\n",count);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(a[i]==j)
printf("Q\t");
else
printf("*\t");
}
printf("\n");
}
}
void queen(n)
{
int k=1;
a[k]=0;
while(k!=0)
{
a[k]++;
while(a[k]<=n && !place(k))
a[k]++;
if(a[k]<=n)
{
if(k==n)
print_sol(n);
else
{
k++;
a[k]=0;
}
}
else
k--;
}
}
void main()
{
int n;
clrscr();
printf("\nEnter the number of queens:");
scanf("%d",&n);
queen(n);
getch();
}
I just want to know how it backtracks automatically?
placemerely checks if the queen in rowposcan be placed in columna[pos].The backtracking is in the
queensfunction, when trying to place the queen in rowk, initially,a[k]is 0, which is not a valid position for the queen