#include<stdio.h>
#include<math.h>
#include"malloc.h"
#define MaxQ 8
typedef struct
{
int x;
int y;
}Pos; //皇后位置
typedef struct node
{
Pos data;
struct node *next;
}Stack;
/*--------*----------*------------*---------*/
Stack * InitStack();
int Push(Stack *top,Pos x) ;
int EmptyStack(Stack *top) ;
int Pop(Stack *top,Pos *e) ;
int GetTopStack(Stack *top,Pos *e);
/*--------*----------*------------*---------*/
//合法:不同行,不同列,不在对角线上-行差和列差绝对值不相等
int Check(int Q[][MaxQ],int x,int y)
{
for(int i=0;i<=x;i++)
for(int j=0;j<MaxQ;j++)
if(Q[i][j]==1)
{
if(i==x||j==y||abs(i-x)==abs(j-y))//如果同行同列同对线,不合法时返回0
return 0;
}
return 1;
}
//打印皇后
void print_Q(int Q[][MaxQ])
{
for(int i=0;i<MaxQ;i++)
{
for(int j=0;j<MaxQ;j++)
printf(" %d",Q[i][j]);
putchar(10);
}
}
void main()
{
int Queen[MaxQ][MaxQ]={0};//棋谱
int count=0;
Stack *S;
Pos D;
S=InitStack();
Queen[0][0]=1;//第一个皇后先放第一个位置
D.x=0; D.y=0;
Push(S,D);
int i=0,j=0;
while(!EmptyStack(S))
{
GetTopStack(S,&D);
i=D.x;// 当前行,即第i+1个皇后,i从0开始
if(i==MaxQ-1)
{
count++;
printf("第%d个解:\n",count);
print_Q(Queen);
}
for(int j=0;j<MaxQ;j++)//当i+1行找到合法位置摆下皇后并进栈
{
if(Check(Queen,i+1,j))
{
D.x=i+1;D.y=j;
Queen[D.x][D.y]=1;
Push(S,D);
break;
}
}
if(j>=MaxQ) //如i+1行穷尽列没找到可以摆放的位置,则退栈
{
while(!EmptyStack(S))
{
Pop(S,&D);
Queen[D.x][D.y]=0;
for(int k=D.y+1;k<MaxQ;k++) //在本行找到下一个位置
if(Check(Queen,D.x,k))
{
D.y=k;
Queen[D.x][D.y]=1;
Push(S,D);
break;
}
if(k<MaxQ)//本行能找到终止此循环,否则继续退栈
break;
}
}
}
printf("%d皇后的解个数:%d\n",MaxQ,count);
}
Stack * InitStack()
{
Stack *top;
top=(Stack *)malloc(sizeof(Stack));
top->next=NULL;
return top;
}
//进栈
int Push(Stack *top,Pos x)
{
Stack *s;
s=(Stack *)malloc(sizeof(Stack));
if(!s) //当s==NULL return 0
return 0;
s->data=x;
s->next=top->next; //新申请空间的指针域保存上一个结点的地址
top->next=s; //头指针域保存新结点地址
return 1;
}
//判断栈空
int EmptyStack(Stack *top)
{
if(top->next==NULL)
return 1;
else
return 0;
}
//出栈
int Pop(Stack *top,Pos *e)
{
Stack *s;
if(EmptyStack(top))
return 0;
s=top->next; //取第一个结点的地址
*e=s->data; //返第一结点数据
top->next=s->next; //头结点指针域存第二结点地址
free(s);
return 1;
}
//取栈顶元素
int GetTopStack(Stack *top,Pos *e)
{
Stack *s;
if(EmptyStack(top))
return 0;
s=top->next;
*e=s->data;
return 1;
}
lisen|八皇后问题代码
最新推荐文章于 2024-04-19 14:13:59 发布