代碼實現
#include<iostream>
#include<cmath>
using namespace std;
int x[21];
int n = 8;
int num = 0;
void Print()
{
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= n; ++j)
{
if (x[i] == j)
{
cout << "Q ";
}
else
{
cout << "X ";
}
}
cout << endl;
}
cout << "- - - - - - - -" << endl;
}
void Queen(int r)
{
if (r == n + 1)
{
Print();
num++;
return;
}
for (int i = 1; i <= n; ++i)
{
bool flag = true;
x[r] = i;
for (int j = 1; j < r; ++j)
{
if (x[j] == x[r] || abs(j - r) == abs(x[j] - x[r]))
{
flag = false;
break;
}
}
if (flag)
{
Queen(r + 1);
}
}
}
int main()
{
Queen(1);
cout << num;
return 0;
}
共92種方法