# [USACO1.5] 八皇后 Checker Challenge
## 题目描述
一个如下的 $6 \times 6$ 的跳棋棋盘,有六个棋子被放置在棋盘上,使得每行、每列有且只有一个,每条对角线(包括两条主对角线的所有平行线)上至多有一个棋子。
![](https://cdn.luogu.com.cn/upload/image_hosting/3h71x0yf.png)
上面的布局可以用序列 $2\ 4\ 6\ 1\ 3\ 5$ 来描述,第 $i$ 个数字表示在第 $i$ 行的相应位置有一个棋子,如下:
行号 $1\ 2\ 3\ 4\ 5\ 6$
列号 $2\ 4\ 6\ 1\ 3\ 5$
这只是棋子放置的一个解。请编一个程序找出所有棋子放置的解。
并把它们以上面的序列方法输出,解按字典顺序排列。
请输出前 $3$ 个解。最后一行是解的总个数。
## 输入格式
一行一个正整数 $n$,表示棋盘是 $n \times n$ 大小的。
## 输出格式
前三行为前三个解,每个解的两个数字之间用一个空格隔开。第四行只有一个数字,表示解的总数。
## 样例 #1
### 样例输入 #1
```
6
```
### 样例输出 #1
```
2 4 6 1 3 5
3 6 2 5 1 4
4 1 5 2 6 3
4
```
## 提示
【数据范围】
对于 $100\%$ 的数据,$6 \le n \le 13$。
题目翻译来自NOCOW。
USACO Training Section 1.5
#include <bits/stdc++.h>
using namespace std;
template <typename T>
T read() {
T sum = 0, fl = 1;
int ch = getchar();
for (; !isdigit(ch); ch = getchar())
if (ch == '-') fl = -1;
for (; isdigit(ch); ch = getchar()) sum = sum * 10 + ch - '0';
return sum * fl;
}
const int MAXN = 15;
int n;
bool row[MAXN], col[MAXN], ld[2*MAXN], rd[2*MAXN]; // true 可占用
inline bool is_available(int i, int j) {
return row[i] && col[j] && ld[i-j+n] && rd[i+j-1];
}
inline void tobe_unavailable(int i, int j) {
row[i] = col[j] = ld[i-j+n] = rd[i+j-1] = false;
}
inline void tobe_available(int i, int j) {
row[i] = col[j] = ld[i-j+n] = rd[i+j-1] = true;
}
int main() {
std::ios::sync_with_stdio(false);
n = read<int>();
int ans = 0;
vector<int> path;
memset(row, 1, sizeof(row));
memset(col, 1, sizeof(col));
memset(ld, 1, sizeof(ld));
memset(rd, 1, sizeof(rd));
function<void(int)> dfs = [&](int i) -> void {
if (i > n) {
++ans;
if (ans <= 3) {
for (int index: path) cout << index << " ";
cout << endl;
}
}
for (int j = 1; j <= n; ++j) {
if (is_available(i, j)) {
tobe_unavailable(i, j);
path.push_back(j);
dfs(i+1);
tobe_available(i, j);
path.pop_back();
}
}
return;
};
dfs(1);
cout << ans << endl;
return 0;
}