-
Problem with n queens
Code:
#include<stdio.h>#include<string.h>
#include<conio.h>
#include<ctype.h>
#include<stdlib.h>
#include<math.h>
int stack1[100];
int stack2[100];
int top=-1;
char queen[100][100];
int empty()
{
if(top==-1)
return 1; //if empty
else
return 0; //if not empty
}
void push(int i,int j) //pushes a value to the top of the stack
{
top+=1;
stack1[top]=i;
stack2[top]=j;
}
void pop()
{
top-=1;
}
int check(int n)
{
int i=0,x=0,y=0,j=0;
int val1,val2;
while(x!=1||top!=-1)
{
for(i=0;i<top;i++)
{
if(stack1[i]==stack1[top]||stack2[i]==stack2[top]||(abs(stack1[i]-stack1[top])==abs(stack2[i]-stack2[top])))
{
if(stack2[top]==n)
{ for(j=0;j<=top;j++)
pop();
}
else
stack2[top]=stack2[top]+1;
}
else if((stack1[i]!=stack1[top])&&(stack2[i]!=stack2[top])&&((abs(stack1[i]-stack1[top]))!=(abs(stack2[i]-stack2[top])))&&(top+1==n))
{
x=1;
return 0;
}
else
{
queen[val1][val2]='Q';
val1=rand()%n;
val2=rand()%n;
push(val1,val2);
}
}
y++;
}
}
int input(int n)
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(queen[i][j]=='0')
{queen[i][j]='Q';
push(i,j);
return 0;}
}
}
}
void reset(int n)
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{ if(queen[i][j]!='Q')
queen[i][j]='.';
}
}
}
void main()
{
int n; //no of Queens
int i=0; //no of row
int j=0; //no of column
int a=0; //counter
clrscr();
printf("Enter the number of Queens: ");
scanf("%d",&n);
printf("\n");
queen[i][j]='Q';
push(i,j);
reset(n);
check(n);
for(i=0;i<n;i++)
{ printf("\n");
for(j=0;j<n;j++)
{
printf(" %c ",queen[i][j]);
}
}
getch();
}
My friend created this program and the program is infite loop I can't fix it.
Please help,
-
If you post code which everybody is able to compile you will greatly enhance your chances that you will get help:
Code:
$ make foo
cc -ggdb3 -Wall -Wextra -c -o foo.o foo.c
foo.c:1:18: warning: extra tokens at end of #include directive [enabled by default]
foo.c:2:18: fatal error: conio.h: No such file or directory
compilation terminated.
make: *** [foo.o] Error 1
Get rid of conio.h and fix your indentation.
You could also try to run the program in a debugger and find out where it is stuck.
Bye, Andreas