注册 登录
编程论坛 C++教室

利用栈解决八皇后问题出现无限循环,求解决

YUN_P 发布于 2014-11-26 22:49, 422 次点击
const int StackSize=8;//设定8个皇后
int ans=0;

template<class T>
class Queen
{
    public:
        Queen(){top=-1;}//初始化空栈
        void Push(T x);//入栈
        void Pop();//出栈
        void PlaceQueen(int n);//放皇后
        bool JudgeQueen();//判断皇后位置
        void Print();//打印位置
        bool Empty()//判断栈是否为空
        {
            if(top==-1)
                return true;
            else
                return false;
        };
    private:
        T data[StackSize];
        int top;
};

template<class T>
void Queen<T>::Push(T x)
{
    if (top >=(StackSize-1)) throw"上溢";
    top++;
    data[top]=x;
};

template<class T>
void Queen<T>::Pop()
{
    if(Empty())throw"下溢";
    top--;
};

template<class T>
void Queen<T>::PlaceQueen(int n)
{
    for(int p=0;p<StackSize;p++)
    {
        Push(p);
        if (JudgeQueen())
        {
            if(n<StackSize-1)
                PlaceQueen(p+1);
            else
            {
                ans++;
                Print();
            }
        }
        Pop();
    }
}

template<class T>
bool Queen<T>::JudgeQueen()
{
    for(int i=0;i<top;i++)
        if(data[top]==data[i]||(abs(data[top]-data[i]))==(top-i))
            return false;
    return true;
};

template<class T>
void Queen<T>::Print()
{
    cout<<"NO."<<ans<<":"<<endl;
    for(int i=0;i<StackSize;i++)
    {
        for(int j=0;j<data[i];j++)
            cout<<"-";
        cout<<"Q";
        for(int j=StackSize-1;j>data[i];j--)
            cout<<"-";
        cout<<endl;
    }
    cout<<endl;
};


#include<iostream>
#include"Queen.h"
#include<Windows.h>
using namespace std;
void main()
{
    Queen<int> Q;
    Q.PlaceQueen(0);
    cout<<"总数"<<ans<<endl;
    system("pause");
}

我运行出来只有一个结果,然后就是后面无限循环。
0 回复
1