八皇后问题——全排列解法
#include <iostream>
#include<algorithm>
using namespace std;
string s[1000000];
int num[9] = {1,2,3,4,5,6,7,8,9};
int main()
{
int x;
cin >> x;
if (x == 1)
{
cout << "Q" << endl;
}
else
{
int e = 0;
do
{
for (int i = 0; i < x; i++)
{
s[e] += (num[i] + '0');
}
e++;
} while (next_permutation(num, num + x));
int n = 0;
for (int i = e - 1; i >= 0; i--)
{
bool b = true;
for (int y = 0; y < x - 1; y++)
{
for (int z = y + 1; z < x; z++)
{
if (int(s[i][y]) == int(s[i][z]) + (z-y))
{
b = false;
break;
}
else if (int(s[i][y]) == int(s[i][z]) - (z-y))
{
b = false;
break;
}
}
if (!b) break;
}
if (b)
{
for (int t = 0; t < x; t++)
{
for (int y = 0; y < x; y++)
{
if (y == int(s[i][t]) - 49)
{
cout << "Q";
}
else
{
cout << ".";
}
}
cout << endl;
}
cout << endl;
}
}
}
}
真好,它们可以飞翔

浙公网安备 33010602011771号