Question: 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?

Answer: 
`place` merely checks if the queen in row `pos` can be placed in column `a[pos]`.

The backtracking is in the `queens` function, when trying to place the queen in row `k`, initially, `a[k]` is 0, which is not a valid position for the queen

```
a[k]++;     // here, a[k] was not a valid position and no smaller was valid, so increment
while(a[k]<=n && !place(k))  // while the position is invalid, check next
    a[k]++;
if(a[k]<=n)  // if a valid column was found
{
    if(k==n) // that was the last row, done
        print_sol(n);
    else     // next row
    {
        k++;
        a[k]=0;
    }
}
else  // no possible column found (a[k] > n), so backtrack
k--;  // check for next possible column in previous row

```
All that `place` does is determine if queen number `pos` can be attacked by any queen with number less than `pos`. It does this by checking if queen #pos is on the same column or diagonal as each of the other queens in turn. Therefore, if `place(pos)` returns `1` it means that the value of `a[pos]` is the zero-based index of a column where the queen can be legally placed.