N皇后问题
//queen.h
class Queen
{
private:
int number;//皇后数
bool *row;//行是否有随机数
bool *diag;//主对角线是否有皇后数
bool *backDiag;//反对角线是否有皇后数
int *x;//解
static int num;//解得个数
//辅助函数
void BackTracking(int c);//回溯法递归求解
void Show();//显示解
public:
Queen();
virtual ~Queen();
void Run();
};
int Queen::num=0;
Queen::Queen()
{
cout<<"请输入皇后数:"<<endl;
cin>>number;
row=new bool[number+1];
diag=new bool[2*number];
backDiag=new bool[2*number];
x=new int[number+1];
int i;
for(i=1;i<=number;i++)
row[i]=false;
for(i=1;i<2*number;i++)
diag[i]=false;
for(i=1;i<2*number;i++)
backDiag[i]=false;
}
Queen::~Queen()
{
delete []row;
delete []diag;
delete []backDiag;
delete []x;
}
void Queen::Run()
{
BackTracking(1);
}
void Queen::Show()
{
cout<<"第"<<++num<<"个解";
cout<<"("<<x[1];
for(int i=2;i<=number;i++)
cout<<","<<x[i];
cout<<")"<<endl;
}
void Queen::BackTracking(int c)
{
if(c>number)
Show();
else
{
for(int r=1;r<=number;r++)
{
if(!row[r]&&!diag[number-c+r]&&!backDiag[r+c-1])
{
row[r]=diag[number-c+r]=backDiag[r+c-1]=true;
x[c]=r;
BackTracking(c+1);
row[r]=diag[number-c+r]=backDiag[r+c-1]=false;
}
}
}
}
//main.cpp
#include "utility.h"
#include"queen.h"
void main()
{
system("color 24");
Timer obj;
Queen objQueen;
objQueen.Run();
cout<<"用时"<<obj.ElapsedTime()<<"秒"<<endl;
system("pause");
}