第六次试验

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值