第一种搜索方式:
按行进行全排列,边排列边剪枝,col,dg,udg(列,对角线,反对角线)
对角线和反对角线有2*n-1个,数组要多开
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 10;
int n;
char g[N][N];
bool col[N], dg[N*2], udg[N*2];
void dfs(int u)
{
if (u == n)
{
for (int i = 0; i < n; i ++) puts(g[i]);
puts("");
return;
}
for (int i = 0; i < n; i ++)
{
if (!col[i] && !dg[i+u] && !udg[i-u+n])
{
g[u][i] = 'Q';
col[i] = dg[i+u] = udg[i-u+n] = true;
dfs(u+1);
col[i] = dg[i+u] = udg[i-u+n] = false;
g[u][i] = '.';
}
}
}
int main()
{
cin >> n;
for (int i = 0; i < n; i ++)
for (int j = 0; j < n; j ++)
g[i][j] = '.';
dfs(0);
return 0;
}
第二种搜索方式:
对每个格子进行选择加不加入皇后,当进行到最后一行的时候检查是否有n个皇后
#include <iostream>
using namespace std;
const int N = 10;
int n;
bool row[N], col[N], dg[N * 2], udg[N * 2];
char g[N][N];
void dfs(int x, int y, int s)
{
if (s > n) return;
if (y == n) y = 0, x ++ ;
if (x == n)
{
if (s == n)
{
for (int i = 0; i < n; i ++ ) puts(g[i]);
puts("");
}
return;
}
g[x][y] = '.';
dfs(x, y + 1, s);
if (!row[x] && !col[y] && !dg[x + y] && !udg[x - y + n])
{
row[x] = col[y] = dg[x + y] = udg[x - y + n] = true;
g[x][y] = 'Q';
dfs(x, y + 1, s + 1);
g[x][y] = '.';
row[x] = col[y] = dg[x + y] = udg[x - y + n] = false;
}
}
int main()
{
cin >> n;
dfs(0, 0, 0);
return 0;
}