question was to solve n queen's problem using backtracking. Using recursion its easy but i am trying to explore it using without recursion.

Errors :

there is no error but some bugs are there. It is giving correct answer for some steps but when backtracking goes to last element it is not giving me correct answer.

What i am trying to do:

i am trying to solve the n queen's problem using backtracking and without recursion. In which i am first blocking the positions and then if not getting positions for next queen backtracking it by unblocking the position of previous queen. here is my code.

/*blocked= queen number unblocked=14 queen placed=16*/ #include<iostream.h> #include<conio.h> #include<math.h> #define MAX 20 void init(int); void place(int*,int); void block_path(int ,int ,int); void unblock(int,int,int); void display(int); int board[MAX][MAX]; int main() { //clrscr(); int n; cout<<"\nEnter number of queens: "; cin>>n; init(n); for(int i=0;i<n;i++) { cout<<"\n"<<i<<"\n"; place(&i,n); cout<<"\n"<<i<<"\n"; display(n); } getch(); return 0; } void init(int n) { for(int i=0;i<n;i++) for(int j=0;j<n;j++) board[i][j]=14; } void place(int *i,int n) { int k,j; for(j=0;j<n;j++) { if(board[(*i)][j]==14) { board[(*i)][j]=16; cout<<"\n("<<*i<<","<<j<<")"; block_path(*i,j,n); return; } else if(j==n-1) { if(*i!=0) *i=*i-1; for(k=0;k<n;k++) { if(board[*i][k]==16) { unblock(*i,k,n); board[*i][k]=14; j=k; break; } } if(j==n-1) { j=-1; if(*i==1) (*i)=0; } } if(*i==n-1) return; } } void block_path(int i,int j,int n) { for(int p=0;p<n;p++) { if(board[i][p]==14&&board[i][p]!=16) { board[i][p]=i; } if(board[p][j]==14&&board[p][j]!=16) { board[p][j]=i; } } for(int q=0;q<n;q++) { for(int k=0;k<n;k++) { if(board[q][k]==14) { if(board[q][k]!=16&&q+k==i+j) board[q][k]=i; } if(board[q][k]==14){ if(board[q][k]!=16&&abs(q-k)==abs(i-j)) board[q][k]=i; } } } } void unblock(int i,int j,int n) { for(int p=0;p<n;p++) { if(board[i][p]==i) board[i][p]=14; if(board[p][j]==i) board[p][j]=14; } for(int q=0;q<n;q++) { for(int k=0;k<n;k++) { if(board[q][k]==i&&q+k==i+j) board[q][k]=14; if(board[q][k]==i&&abs(q-k)==abs(i-j)) board[q][k]=14; } } } void display(int n) { for(int i=0;i<n;i++) { cout<<"\n"; for(int j=0;j<n;j++) { cout<<"\t"<<board[i][j]; } cout<<"\n"; } }