n-皇后问题
1.用dfs遍历每一行皇后的位置
#include <iostream>
using namespace std;
const int N = 10;
int n;
char h[N][N];
bool col[N],dg[N],udg[N];
void dfs(int u)
{
if(u == n)
{
for(int i = 0;i<n;i++) puts(h[i]);
printf("\n");
return;
}
for(int i = 0;i<n;i++)
{
if(!col[i] && !dg[u + i] && !udg[ n - u + i])
{
h[u][i] = 'Q';
col[i] = dg[u + i] = udg[n - u + i] = true;
dfs(u + 1);
h[u][i] = '.';
col[i] = dg[u + i] = udg[n - u + i] = false;
}
}
}
int main()
{
scanf("%d",&n);
for(int i = 0;i<n;i++)
for(int j = 0;j<n;j++)
h[i][j] ='.';
dfs(0);
return 0;
}
2.遍历每一个格子有无皇后的可能性
#include <iostream>
using namespace std;
const int N = 10;
int n;
char h[N][N];
bool row[N],col[N],dg[N],udg[N];
//x是行,y是列,s是皇后的个数
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(h[i]);
printf("\n");
}
return;
}
//不放皇后
dfs(x,y+1,s);
//放皇后
if(!row[y] && !col[x] && !dg[x + y] && !udg[x - y + n])
{
h[x][y] = 'Q';
row[y] = col[x] = dg[x + y] = udg[x - y + n] = true;
dfs(x,y+1,s+1);
h[x][y] = '.';
row[y] = col[x] = dg[x + y] = udg[x - y + n] = false;
}
}
int main()
{
scanf("%d",&n);
for(int i = 0;i<n;i++)
for(int j = 0;j<n;j++)
h[i][j] ='.';
dfs(0,0,0);
return 0;
}