八皇后
题目:输入一个n,代表n*n的棋盘(6 <= n <= 13),在棋盘上放置皇后,每行每列每条左右对角线只可有一个棋子,求总方案数,以及按行输出前三种棋子摆放的列数
思路:dfs深度搜索按行搜索,dfs内遍历每一列,判断是否可摆放
#include <iostream>
using namespace std;
const int maxn = 100;
int a[maxn],b[maxn], c[maxn],d[maxn];
//a为每行棋子摆放的列数,b为每列是否有棋子
//c为左对角线是否有棋子,d为右对角线是否有棋子
int ans = 0, n;
void dfs(int st)
{
if(st > n)
{
ans++;
if(ans <= 3)
{
for(int i = 1; i <= n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
return ;
}
for(int i = 1; i <= n; i++)
{
if(b[i] == 0 && c[st - i + n] == 0 && d[i + st] == 0)
{
a[st] = i;
b[i] = 1;
c[st - i + n] = 1;
d[i + st] = 1;
dfs(st + 1);
a[st] = 0;
b[i] = 0;
c[st - i + n] = 0;
d[i + st] = 0;
}
}
}
int main()
{
cin >> n;
dfs(1);
cout << ans;
return 0;
}