数据结构上机实验3——N皇后问题栈求解

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MaxSise 100
int cont=0;
typedef struct
{
    int col[MaxSise];
    int top;
} StType;
int count=0;
bool place(StType st,int i,int j)
{
    int k=1;
    if(i==1)
        return true;
    while(k<=i-1)
    {
        if((st.col[k]==j)||(abs(j-st.col[k])==abs(k-i)))
            return false;
        k++;
    }
    return true;
}
void queen(int n)
{
    int  i,j,k;
    bool find;
    StType st;
    st.top=0;
    st.top++;
    st.col[st.top]=1;
    while(st.top>0)
    {
        i=st.top;
        if(st.top==n)
        {
            printf(" 第%d个解:",++count);
            for(k=1;k<=st.top;k++)
            {
                printf(" <%d,%d> ",k,st.col[k]);
            }
            printf("\n");
        }
        find=false;
        for(j=1; j<=n; j++)

            if(place(st,i+1,j))
            {
                st.top++;
                st.col[st.top]=j;
                find=true;
                break;
            }
        if(find==false)
        {
            while(st.top>0)
            {
                if(st.col[st.top]==n)
                    st.top--;
                for(j=st.col[st.top]+1; j<=n; j++)
                    if(place(st,st.top,j))
                    {
                        st.col[st.top]=j;
                        break;
                    }
                if(j>n)
                    st.top--;
                else
                    break;
            }
        }
    }
}
int main()
{
    int n;
    printf("皇后问题<n<20> n=");
    scanf("%d",&n);
    if(n>20)
    {
        printf("n值太大,不能求解\n");
    }
    else
    {
        printf("%d皇后问题求解如下:\n",n);
        queen(n);
        printf("\n");
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值