C++解八皇后问题
引用:
八皇后问题,是一个古老而著名的问题,是回溯算法的典型例题。该问题是十九世纪著名的数学家高斯1850年提出:在8X8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。 高斯认为有76种方案。1854年在柏林的象棋杂志上不同的作者发表了40种不同的解,后来有人用图论的方法解出92种结果。计算机发明后,有多种方法可以解决此问题。
下面是我给出的C++解法:
#include<iostream>
#include<iomanip>
#include<fstream>
#define eqa(x) x+eq[x]
#define eqb(x) x-eq[x]
void eqpermute(int[]);
void eqpermute(int[],int,int);
void eqshow(int[]);
void eqswap(int[],int,int);
bool eqcheck(int[]);
int count=0;
std::ofstream outfile("D:\\eight-queen.txt",std::ios::trunc);
int main(){
int eq[8]={0,1,2,3,4,5,6,7};
eqpermute(eq);
system("pause");
}
void eqpermute(int eq[]){
eqpermute(eq, 0, 7);
}
void eqpermute(int eq[], int low, int high){ //Permute all the permutations.(Recursion)
if(low==high){
//std::cout<<eq[0]<<eq[1]<<eq[2]<<eq[3]<<eq[4]<<eq[5]<<eq[6]<<eq[7]<<std::ends;
if(eqcheck(eq))
eqshow(eq);
}
else{
for(int i=low; i<=high ;i++){
eqswap(eq, low, i);
eqpermute(eq, low+1, high);
eqswap(eq, low, i);
}
}
}
void eqshow(int eq[]){
using namespace std;
outfile<<"EIGHT QUEEN "<<setfill('0')<<setw(4)<<++count<<endl;
for(int i=0;i<8;++i){
for(int j=0;j<eq[i];++j)
outfile<<"□";
outfile<<"■";
for(int j=eq[i]+1;j<8;++j)
outfile<<"□";
outfile<<endl;
}
}
void eqswap(int eq[],int a,int b){
int temp = eq[a];
eq[a] = eq[b];
eq[b] = temp;
}
bool eqcheck(int eq[]){
int a[] = {eqa(0),eqa(1),eqa(2),eqa(3),eqa(4),eqa(5),eqa(6),eqa(7)};
int b[] = {eqb(0),eqb(1),eqb(2),eqb(3),eqb(4),eqb(5),eqb(6),eqb(7)};
bool isOK = true;
for(int i=0;i<7;++i)
for(int j=i+1;j<8;++j)
if(a[i]==a[j])
isOK = false;
for(int i=0;i<7;++i)
for(int j=i+1;j<8;++j)
if(b[i]==b[j])
isOK = false;
return isOK;
}