codeup26700_N皇后问题
时空限制 1000ms/128MB
题目描述
在N*N的棋盘上放置N个皇后(n<=10)而彼此不受攻击(即在棋盘的任一行,任一列和任一对角线上不能放置2个皇后),编程求解所有的摆放方法。
输入格式
输入:n
输出格式
每行输出一种方案,每种方案顺序输出皇后所在的列号,各个数之间有空格隔开。若无方案,则输出no solute!
输入样例
4
输出样例
2 4 1 3
3 1 4 2
代码
#include<iostream>
using namespace std;
const int N = 15;
int n,a[N],tot=0;
bool b[N],c[2*N],d[2*N];
void search(int i){
if (i>n){
tot++;
for (int i=1; i<n; i++) cout<<a[i]<<" ";
cout<<a[n]<<endl;
return;
}
for (int j=1; j<=n; j++)
if (!b[j] && !c[i+j] && !d[i-j+n]){
a[i] = j;
b[j] = c[i+j] = d[i-j+n] = true;
search(i+1);
b[j] = c[i+j] = d[i-j+n] = false;
}
}
int main(){
ios::sync_with_stdio(false);
cin>>n;
search(1);
if (!tot) cout<<"no solute!\n";
return 0;
}