栈和队列的基本运算实现
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;
}
运行结果:
要求:(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;
}
运行结果:
相关文章推荐
- 有关数据库SQL递归查询在不同数据库中的实现方法
- C#中的递归APS和CPS模式详解
- C#使用回溯法解决背包问题实例分析
- WinForm实现按名称递归查找控件的方法
- 使用SqlServer CTE递归查询处理树、图和层次结构
- C#中的尾递归与Continuation详解
- C#递归实现显示文件夹及所有文件并计算其大小的方法
- php递归创建目录的方法
- PHP递归创建多级目录
- Javascript递归打印Document层次关系实例分析
- javascript递归回溯法解八皇后问题
- oracle 使用递归的性能提示测试对比
- 使用curl递归下载软件脚本分享
- Perl脚本实现递归遍历目录下的文件
- JavaScript的递归之递归与循环示例介绍
- C# 递归查找树状目录实现方法
- 全排列算法的非递归实现与递归实现的方法(C++)
- php递归列出所有文件和目录的代码
- java递归菜单树转换成pojo对象
- Python:打印某个路径下的所有文件