题目描述
经典问题。
N皇后问题(加强版)
皇后们想知道自己到底有多少种排列方式。
国际象棋中规定:
皇后对角线互能攻击。
有两个皇后位于同一行或者同一列都不符合要求。!
也就是说,把N个棋子被放置在棋盘上,使得每行、每列只有一个,每条对角线(包括两条主对角线的所有对角线)上至多有一个棋子
下面给出一个例子
列号
1 2 3 4 5 6
-------------------------
1 | | O | | | | |
-------------------------
2 | | | | O | | |
-------------------------
3 | | | | | | O |
-------------------------
4 | O | | | | | |
-------------------------
5 | | | O | | | |
-------------------------
6 | | | | | O | |
-------------------------
'O'表示皇后,
这样是一个符合要求的方法。
其中,上面的布局可以用序列2 4 6 1 3 5来描述,第i个数字表示在第i行的相应位置有一个棋子,如下:
行号 1 2 3 4 5 6
列号 2 4 6 1 3 5
我们要求的就是输出方案每个皇后的列号!
输出: 前3种排列方案,
共有多少种排列方案!!
输入格式
读入N,其中(4<=N<=13).
表示棋盘是N x N.
输出格式
前3行为N皇后的前3种排列。用空格隔开。
(若不足3种全部输出)
第4行为共有多少种排列。
样例输入
6
样例输出
2 4 6 1 3 5
3 6 2 5 1 4
4 1 5 2 6 3
4
一道基礎的深搜,考察深搜框架。
ACCode:
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <bitset>
using std::bitset;
const char fi[] = "rqnoj589.in";
const char fo[] = "rqnoj589.out";
const int maxN = 20;
const int MAX = 0x3fffff00;
const int MIN = -MAX;
bitset <maxN> lx;
bitset <maxN << 1> L1;
bitset <maxN << 1> L2;
int g[maxN];
int n, tot;
void init_file()
{
freopen(fi, "r", stdin);
freopen(fo, "w", stdout);
}
void readdata()
{
scanf("%d", &n);
}
void count()
{
++tot;
if (tot < 4)
{
for (int i = 1; i < n; ++i)
printf("%d ", g[i]);
printf("%d\n", g[n]);
}
}
void Dfs(int i)
{
if (i > n) count();
for (int j = 1; j < n + 1; ++j)
{
if (lx.test(j)) continue;
if (L1.test(i + j)) continue;
if (L2.test(i - j + n)) continue;
lx.set(j);
L1.set(i + j);
L2.set(i - j + n);
g[i] = j;
Dfs(i + 1);
g[i] = 0;
lx[j] = 0;
L1[i + j] = 0;
L2[i - j + n] = 0;
}
}
void work()
{
tot = 0;
Dfs(1);
printf("%d", tot);
}
int main()
{
init_file();
readdata();
work();
exit(0);
}