问题 D: 【递归入门】n皇后 问题(原始的8皇后问题)
时间限制: 1 Sec 内存限制: 128 MB
提交: 178 解决: 88
[提交][状态][讨论版][命题人:外部导入]
题目描述
会下国际象棋的人都很清楚:皇后可以在横、竖、斜线上不限步数地吃掉其他棋子。如何将8个皇后放在棋盘上(有8 * 8个方格),使它们谁也不能被吃掉!这就是著名的八皇后问题。
输入
一个整数n( 1 < = n < = 10 )
输出
每行输出对应一种方案,按字典序输出所有方案。每种方案顺序输出皇后所在的列号,相邻两数之间用空格隔开。如果一组可行方案都没有,输出“no solute!”
样例输入
4
样例输出
2 4 1 3 3 1 4 2
#include<iostream>
using namespace std;
int n, a[10];
bool flag[10] = { false };
bool no;
void DFS(int index) {
for (int i = 0; i < index - 1; i++) {//剪枝
for (int j = i + 1; j < index; j++) {
if (i - j == a[i] - a[j] || a[i] + i == a[j] + j)
return;
}
}
if (index == n) {
for (int i = 0; i < n; i++) {
cout << a[i] + 1 << " ";
}
cout << endl;
no = false;
return;
}
for (int i = 0; i < n; i++) {
if (!flag[i]) {
a[index] = i;
flag[i] = true;
DFS(index + 1);
flag[i] = false;
}
}
}
int main() {
while (cin >> n) {
no = true;
DFS(0);
if (no) cout << "no solute!" << endl;
}
return 0;
}