n皇后问题
n个皇后放在n*n的棋盘上,使得皇后不能相互攻击到,即任意两个皇后
都不能处于同一行,同一列或同一斜线上
1.输入n (表示棋盘大小)
2.输出所有符合条件的结果“Q”代表皇后,“.”代表棋盘中的空格
暴力方法
#include<bits/stdc++.h>
using namespace std;
const int N = 20;
int n;
char g[N][N];
bool col[N], dg[N], udg[N], row[N];
// col代表第i行是否放置元素
// dg代表第i条对角线是否放置元素
// udg代表第i条反对角线是否放置元素
void dfs(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 ++) puts(g[i]);
puts("");
}
return;
}
//不放皇后
dfs(x, y + 1, s);
//放皇后
if(!row[x] && !col[y] && !dg[x + y] && !udg[x - y + n])
{
g[x][y] = 'Q';
row[x] = col[y] = dg[x + y] = udg[x - y + n] = true;
dfs(x , y + 1, s + 1);
row[x] = col[y] = dg[x + y] = udg[x - y + n] = false;
g[x][y] = '.';
}
}
int main()
{
cin >> n;
for(int i = 0; i < n; i ++)
{
for(int j = 0; j < n ; j ++ ) g[i][j] = '.';
}
dfs(0 , 0, 0);
return 0;
}
深度搜索方法
#include<bits/stdc++.h>
using namespace std;
const int N = 20;
int n;
char g[N][N];
bool col[N], dg[N], udg[N];
// col代表第i行是否放置元素
// dg代表第i条对角线是否放置元素
// udg代表第i条反对角线是否放置元素
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[u + i] && !udg[n - u + i])
{
g[u][i] = 'Q';
col[i] = dg[u + i] = udg[n - u + i] = true;
dfs(u + 1);
col[i] = dg[u + i] = udg[n - u + i] = 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;
}