Code :
#include
#include
#define QUEENNO 8
void placeQueen(int,int *);
int canBePlaced(int,int,int *);
void showBoard(int *);
main(){
int x[QUEENNO],i;
printf("The 8 Queens problems
");
placeQueen(0,x); /* start placing with the first Queen */
printf("end");
}
void placeQueen(int k,int *x){
int i,j;
char ch;
for(i=0;i<8;i++){
if(canBePlaced(k,i,x)){ /* can we place the k th Queen at the i th
column ? */
x[k]=i; /* place the k th Queen at i th column */
if(k==7){
showBoard(x); /* one result is found, show the board */
printf("Want to see more? [n->stop, any->continue] : ");
scanf("%c",&ch);
if(ch=='n' || ch=='N') exit(0);
}
if(k<7) placeQueen(k+1,x); /* still more Queens left, go for them
*/}
}
}
int canBePlaced(int k,int i,int *x){
int j;
for(j=0;j
return 0;
}
return 1;
}
void showBoard(int *x){
int i,j;
printf("-------------------------------------------------------");
printf(" ");
for(i=0;i<8;i++) printf("%d ",(i+1));
printf("");
for(i=0;i<8;i++){
printf("%d ",(i+1));
for(j=0;j<8;j++){
if(j==x[i])
printf("Q");
else printf("-");
printf(" ");
}
printf("");
}
printf("-------------------------------------------------");
}
No comments:
Post a Comment