# N皇后问题的一个程序，请大家看看！帮忙修改

#include <stdio.h>
#include <iostream.h>
#include <iomanip.h>
#include <math.h>
class Queen{
friend int nQueen(int);
private: bool Place(int k);
void Backtrack(int t);
void display(); int n, //皇后个数
* x;  //当前解
long sum; //当前已找到的可行方案};
bool Queen::Place(int k)
{  for (int j=1;j<k;j++)
if ((abs(k-j)==abs(x[j]-x[k]))||(x[j]==x[k]))
//不满足隐约束
return false; return true;
}
void  Queen::Backtrack(int t)
{
if (t>n)
{
sum++;  //到达叶结点，搜索到一个解
display();
cout<<'\n';
}    else
for (int i=1;i<=n;i++)
{        x[t]=i;
if (Place(t)) Backtrack(t+1);
}
}
void Queen::display( ){
//输出n个皇后在棋盘图形上的位置
int i,j;
int queenq[100][100];
for ( i=1; i<=n; i++)
for ( j=1; j<=n; j++)
queenq[i][j] =0;
//初始化棋盘图形矩阵
for ( i=1; i<=n; i++)
if (x[i]) queenq[i][x[i]] =1;
//为棋盘图形矩阵赋值
for( i=1;i<=n;i++){
//输出棋盘图形
cout << "(" <<" ";
for ( j = 1; j<=n; j++)
if(queenq[i][j]) cout << "Q" << "  ";
else cout << "*" << "  ";
cout << ")" << endl;

}
}
int nQueen(int n)
{
Queen X;
X.n = n;
X.sum = 0;
int *p = new int [n+1];
for (int i = 0; i<=n; i++)
p[i] = 0;
X.x = p;
X.Backtrack(1);
delete [] p;
return X.sum;
}
void main( )
{
int n,sum;
while(1)
{
cout << "用递归回溯法解n后问题"<<"\n"<<endl;
cout << "请输入皇后的数目(不超过16个):  ";
cin >> n;
sum = nQueen(n);

cout << "一共有"<<sum<<"种情况"<<endl;
cout<<"\n"<<endl;
}
}
02-02
08-09 333

08-06 73
04-18 139
11-10 609
11-08 6万+
12-03 4509
05-27 5529