代码实现
#include <iostream>
#include <cstring>
using namespace std;
const int N = 10;
int n;
char path[N][N];
bool cal[N], dg[N * 2], udg[N * 2];
void dfs(int x)
{
if (x > n)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
cout << path[i][j];
cout << endl;
}
cout << endl;
return;
}
for (int y = 1; y <= n; y++)
{
if (!cal[y] && !dg[y + x] && !udg[y - x + n])
{
cal[y] = dg[y + x] = udg[y - x + n] = true;
path[x][y] = 'Q';
dfs(x + 1);
cal[y] = dg[y + x] = udg[y - x + n] = false;
path[x][y] = '.';
}
}
return;
}
int main()
{
memset(path, '.', sizeof(path));
cin >> n;
dfs(1);
return 0;
}