#include <iostream>
using namespace std;
int n;
char path[20][20];
int col[20], row[20], dg[20], udg[20];
//优化算法,每一层只能有一个皇后,所以遍历每一行即可
void dfs(int u)
{
if (u == n)
{
for (int i = 0; i < n; i++)
{
printf(“%s”, path[i]);
printf(“\n”);
}
puts(“”);
return;
}
for (int i = 0; i < n; i++)
{
if (!col[i] && !dg[i + u] && !udg[n – u + i])
{
path[u][i] = ‘Q’;
col[i] = dg[u + i] = udg[n – u + i] = 1;
dfs(u + 1);
col[i] = dg[u + i] = udg[n – u + i] = 0;
path[u][i] = ‘.’;
}
}
}
//底层枚举算法,也就是每一个格子都遍历检查一遍
void dfs2(int x, int y, int s)
{
if (y == n)
y = 0, x++;
if (x == n)
{
if (s == n)
{
for (int i = 0; i < n; i++)
{
printf(“%s”, path[i]);
printf(“\n”);
}
printf(“\n”);
}
return;
}
//不放皇后
dfs2(x, y + 1, s);
if (!row[x] && !col[y] && !dg[x + y] && !udg[x – y + n])
{
path[x][y] = ‘Q’;
row[x] = col[y] = dg[x + y] = udg[x – y + n] = 1;
dfs2(x, y + 1, s + 1);
row[x] = col[y] = dg[x + y] = udg[x – y + n] = 0;
path[x][y] = ‘.’;
}
}
int main()
{
scanf(“%d”, &n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
path[i][j] = ‘.’;
// dfs(0);
// dfs2(0, 0, 0);
dfs(0);
return 0;
}