Eight queens problem

Status
Not open for further replies.

i_learn

In Runtime
Messages
114
hey ppl....i wanted to try the eight queens problem, and i tho of doing it like the goal seeking method. it will explore one route, and if it does nto work , will come back to the last decision made and change it....

the problem is i am getting a stack fault in tcWIN, and in TC dos i get pc beeps, and the program quits....this demads a lot of processor time i realize, but it should work, the logic works on paper... please point out where i am going wrong.


---------------------------------------------------------------------------
#include<stdio.h>
#include<conio.h>
#define p printf
#define s scanf


enum bool{False,True};

//extern declarations

char board[8][8];
int check=0;
int last_row=0;
int last_column=0;


//stack used to record grid locations of placed queens
struct track
{
int row[8], column[8];
int top;
}s1;



//Stack Functions

void push(struct track *ps,int r, int c)
{
ps->row[++ps->top]=r;
ps->column[ps->top]=c;
check++;
}

void pop(struct track *ps)
{
last_row=ps->row[ps->top];
last_column=ps->column[ps->top];
ps->top--;
check--;
}



//Fuction main


void main()
{
void place(int , int);
int i,j,r,c;
s1.top=-1;
void queens(int , int);

p("enter starting square \n");
s("%d %d",&r,&c);

//setting elements on board to 'X'

for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
board[j]='X';
}

// Function call to recursive function
queens(r+1,c+1);


clrscr();


//displaying

for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
p("\t%c",board[j]);
p("\n\n\n");
}
getch();
}


//Function to see if the grid square is in danger to be attacked by any placed queens

bool attack(int r, int c)
{
int i,j=0;
for(i=0;i<8;i++)
{
if(board[r]=='q' || board[c]=='q' || board[r-i][c-i]=='q' || board[r+i][c+i]=='q'|| board[r-i][c+i]=='q' || board[r+i][c-i]=='q')
j=1;
}
if(j==1)
return True;
else
return False;
}



//function to place the queen


void place(int r, int c)
{
if(!attack(r,c))
{board[r][c]='q';
push(&s1,r,c);
}

}


//function to remove queen and continue from next grid
void remove()
{

pop(&s1);
board[last_row][last_column]='X';
}


//recursive function


void queens(int r, int c)
{

if(check==8) //if all queens are placed
return;
if(r==7 && c==7 && check !=8) //if the board is
// exhausted and all queens not placed
{
remove();
r=last_row;c=last_column;
queens(r+1,c);
}
if(r==7 && c!=7 && check!=8) //if the rows are //exhausted in a column
{
queens(0,c+1);
}
place(r,c); //no condition-- place

queens(r+1,c); // call function again for next row in same column
}

--------------------------------------------------------------------------
there are no errors in syntax. for ne one who doesnot know the eight queens problem....read the next post.
 
The Eight Queen problem,

on a chess board u have to place 8 queens such that they may not be attacked by any other queen.

simple no???
 
Status
Not open for further replies.
Back
Top Bottom