#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
int count = 0;
vector<int> queen(8);
class Queen
{
public:
void EightQueen(int n);
//求解八皇后的主干程序
void ShowAnswer();
//用于输出结果
int Check(int n);
//用于检测这一步的棋是否正确
};
void Queen :: EightQueen(int n) //回溯法,递归求解八皇后问题
{
if(n == 8){
ShowAnswer();
return;
}
for(int i = 0; i <= 7; i++){
queen[n] = i;
if(Check(n) ){ //检验该行
EightQueen(n + 1); //若符合,求解下一行
}
}
}
int Queen :: Check(int n) //检验
{
for(int i = 0; i < n; i++){
if(queen[i] == queen[n])
return 0;
if(abs(queen[i] - queen[n]) == abs(n - i))
return 0;
}
return 1;
}
void Queen :: ShowAnswer() //输出结果
{
count++;
cout << "第" << count << "种" << endl;
for(int i = 0; i < 8; i++){
for(int j = 0; j < 8; j++){
if(queen[i] == j)
cout <<"⊙";
else
cout << "■";
}
cout << endl;
}
cout <<endl << endl << endl;
}
int main()
//测试程序
{
Queen Eight_Queen;
Eight_Queen.EightQueen(0);
//第0行开始,求八皇后
cout << count << endl;
}