#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#define MaxSize 100
typedef int ElemType;
int n,num=1;
typedef struct
{
ElemType data[MaxSize];
int top; //栈指针
} SqStack; //声明顺序栈类型
void InitStack(SqStack *&s) //初始化顺序栈
{
s=(SqStack *)malloc(sizeof(SqStack));
s->top=1;
}
void DestroyStack(SqStack *&s) //销毁顺序栈
{
free(s);
}
bool StackEmpty(SqStack *s) //判断栈空否
{
return(s->top==0);
}
bool Push(SqStack *&s,ElemType e) //进栈
{
if (s->top==MaxSize-1) //栈满的情况,即栈上溢出
return false;
s->top++;
s->data[s->top]=e;
return true;
}
bool Pop(SqStack *&s,ElemType &e) //出栈
{
if (s->top==-1) //栈为空的情况,即栈下溢出
return false;
e=s->data[s->top];
s->top--;
return true;
}
bool GetTop(SqStack *s,ElemType &e) //取栈顶元素
{
if (s->top==0) //栈为空的情况,即栈下溢出
return false;
e=s->data[s->top];
return true;
}
void display(SqStack *&st){
printf("第%d个解:",num++);
for(int i=1;i<=n;i++)
printf("(%d,%d)",i,st->data[i]);
printf("\n");
}
bool check(SqStack *&st,int k,int j){
int i=1;
if(k==1) return true;
while(i<=k-1){
if((st->data[i]==j)||(abs(st->data[i]-j)==abs(i-k)))
return false;
i++;
}
return true;
}
void solve(SqStack *&st){
st->top=1;
st->data[st->top]=0;
bool flag;
while(!StackEmpty(st)){
int k=st->top;
flag=false;
for(int j=st->data[k]+1;j<=n;j++){
if(check(st,k,j)){
st->data[k]=j;
flag=true;
break;
}
}
if(flag){
if(k==n) display(st);
else{
st->top++;
st->data[st->top]=0;
}
}
else st->top--;
}
if(num==1) printf("无解\n");
}
int main(){
SqStack *st;
InitStack(st);
scanf("%d",&n);
solve(st);
return 0;
}
第六次试验
最新推荐文章于 2020-12-23 20:12:11 发布