64,664
社区成员
发帖
与我相关
我的任务
分享
//用回溯法递归求解八皇后问题。
#include <iostream>
using namespace std;
void init(bool *row,bool *diag,bool *bdiag,int n);
void show(int *x,int n);
void backtracking(bool *row,bool *diag,bool *bdiag,int *x,int c,int n);
void main()
{
int n,c=1;
cout<<"Input a integer:";
cin>>n;
bool *row=new bool[n];
bool *diag=new bool[2*n];
bool *bdiag=new bool[2*n];
int *x=new int[n];
init(row,diag,bdiag,n);
backtracking(row,diag,bdiag,x,c,n);
delete []row; //输出结果后,出现Debug error!
delete []diag;
delete []bdiag;
delete []x;
}
void backtracking(bool *row,bool *diag,bool *bdiag,int *x,int c,int n)
{
if(c>n)
show(x,n);
else
{
for(int r=1;r<=n;r++)
{
if(!row[r] && !diag[r+c-1] && !bdiag[n-c+r])
{
row[r]=diag[r+c-1]=bdiag[n-c+r]=true;
x[c]=r;
backtracking(row,diag,bdiag,x,c+1,n);
row[r]=diag[r+c-1]=bdiag[n-c+r]=false;
}
}
}
}
void show(int *x,int n)
{
static int i=1;
cout<<"The NO."<<i++<<" root is:(";
for(int j=1;j<=n;j++)
{
cout<<x[j];
if(j!=n)
cout<<',';
else cout<<')'<<endl;
}
}
void init(bool *row,bool *diag,bool *bdiag,int n)
{
for(int k=1;k<=n;k++)
row[k]=false;
for(k=1;k<=2*n;k++)
{
diag[k]=false;
bdiag[k]=false;
}
}
void init(bool *row,bool *diag,bool *bdiag,int n)
{
for(int k=1;k<=n;k++)//我已经加了等号啊。而且按你的改法,我试了,还是出现debug error!
row[k]=false;
for(k=1;k<=2*n;k++)
{
diag[k]=false;
bdiag[k]=false;
}
}