八皇后问题如何用c++解答?

来源:百度知道 编辑:UC知道 时间:2024/06/14 07:55:54
只要c++的源代码,要把各种情况都输出。

//n皇后问题
#include <iostream.h>
#include <iomanip.h>
#include <conio.h>
#define n 8

int a[n+1],c[n+1];
int l[2*n],r[2*n+1];
int count=0;

void place(int i)
{
int j,k;
for(j=1;j<=n;j++)
{
if((c[j]==1)&&(l[i-j+n]==1)&&(r[i+j]==1))
{
a[i]=j;
c[j]=0;
l[i-j+n]=0;
r[i+j]=0;
if(i<n)
place(i+1);
else
{
for(k=1;k<=n;k++)
cout<<setw(4)<<a[k];
count++;
cout<<" count="<<count<<endl;
if(count%20==0)
{
cout<<"Press any key to continue."<<endl;
getch();
}
}
c[j]=1;
l[i-j+n]=1;