您的位置:首页 > 其它

栈和队列的基本运算实现

2016-04-18 10:52 567 查看
编写一个程序exp3-6.cpp,求解皇后问题:在n×n的方格棋盘上,放置n个皇后,要求每个皇后不同行、不同列、不同左右对角线。
要求:(1)皇后的个数n由用户输入,其值不能超过20,输出所有的解。(2)采用类似于栈求解迷宫问题的方法。

#include <iostream>
#include <cstdio>
#include <ctime>
#include <cstdlib>
#define maxsize 20
using namespace std;

int count=0;//计数器

class SqStack
{
private:
int data[maxsize];
int top;
public:
SqStack()
{
top=-1;
}
void Push(int,int);
void Pop();
void Show(int);
void Mothed(int,int);
bool Judge(int);
bool Empty()
{
if(top==-1) return true;
else return false;
}

};

void SqStack::Push(int x,int n)//入栈操作
{
if(top>=n-1)
cerr<<"error"<<endl;
top++;
data[top]=x;
}

void SqStack::Pop()//出栈操作
{
if(Empty())
cerr<<"error"<<endl;
top--;
}

bool SqStack::Judge(int k)// 判断皇后k放在x[k]列是否发生冲突
{
for(int i=0; i<top; i++)
if(data[top]==data[i]||(abs(data[top]-data[i]))==(top-i))
return false;
return true;
}

void SqStack::Mothed(int n,int row)//放置皇后,进行递归
{
for (int col=0; col<n; col++)
{
Push(col,n);
if (Judge(row))
{
if (row<n-1)
Mothed(n,row+1);
else
{
count++;
Show(n);
}
}
Pop();
}
}

void SqStack::Show(int n)//打印皇后序列
{
cout<<"第"<<count<<"个解:";
for (int i=1; i<=n; i++)
{
cout<<"("<<i<<","<<data[i-1]+1<<")"<<" ";
}
cout<<endl;
}

int main()
{
int n;
cout<<"皇后问题(n<20) n=";
cin>>n;
SqStack queen;
queen.Mothed(n,0);
return 0;
}
运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  八皇后 回溯法 递归