Implementation of N-Queens using stack through backtracking.
Tig said
Mar 11, 2016
Hi Rohan,
I'm sorry but you have mistaken our forum, which deals with Hepatitis C for a programming/code forum. We can't help you. Good luck!
Cable Anna said
Mar 11, 2016
/*
hey guys can someone please help me with the following code, it is wrong but i dont understand how to correct it. Where am i wrong?? Is this code on the right path ?? Can it be corrected??
Hi Rohan,
I'm sorry but you have mistaken our forum, which deals with Hepatitis C for a programming/code forum. We can't help you. Good luck!
/*
hey guys can someone please help me with the following code, it is wrong but i dont understand how to correct it. Where am i wrong?? Is this code on the right path ?? Can it be corrected??
*/
#include<stdio.h>
int top=-1;
int x;
typedef struct stack
{
int r,c;
}stack;
stack s[16];
int ispossible(int n,char board[][n],int i,int j)
{
int y,w=i,t=j;
for(y=1;y<=n;y++)
{
if(board[y][j]=='Q')
return 0;
if(board[y]=='Q')
return 0;
}
while(w!=n&&t!=n)
{
w++;
t++;
if(board[w][t]=='Q')
return 0;
}
w=i,t=j;
while(w!=1&&t!=1)
{
w--;
t--;
if(board[w][t]=='Q')
return 0;
}
w=i,t=j;
while(w!=n&&t!=1)
{
w++;
t--;
if(board[w][t]=='Q')
return 0;
}
w=i,t=j;
while(w!=1&&t!=n)
{
w--;
t++;
if(board[w][t]=='Q')
return 0;
}
return 1;
}
void print(int n,char board[][n])
{
int i,j;
printf("\nSolution %d:\n",x);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%c\t",board[j]);
}
printf("\n");
}
}
void push(stack s1,int n)
{
if(top==n)
printf("\nStack full!\n");
else
{
s[++top]=s1;
}
}
stack pop()
{
if(top==-1)
printf("\nStack empty!!\n");
else
{
return s[top--];
}
}
void main()
{
int i,j,l,n,k,m,f;
printf("\nEnter the number of queens:\n");
scanf("%d",&n);
int count;
stack s;
char board[n][n];
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
board[j]='-';
print(n,board);
i=1;
do
{
j=1;
do
{
if(board[j]!='Q'&&ispossible(n,board,i,j))
{
s.r=i;
s.c=j;
push(s,n);
board[j]='Q';
break;
}
else if(board[j]!='Q'&&!ispossible(n,board,i,j))
{
continue;
}
else if(j==n&&!ispossible(n,board,i,j)&&board[j]!='Q')
{
f=0;
do{
if(top==-1)
break;
s=pop();
l=s.c;
m=s.r;
if(l!=n)
l++;
else{
continue;
}
while(l<=n&&ispossible(n,board,m,l))
{
s.r=m;
s.c=l;
board[m][l]='Q';
push(s,n);
f=1;
if(f!=0)
i=m+1;
else
i++;
break;
}
else{
l++;
}
}while(1);
}while(j<=n);
x++;
print(n,board);
}while(i<=n);
}
-- Edited by Tig56 on Friday 11th of March 2016 06:04:29 PM