题目
06:N Queens
查看提交统计提问
总时间限制: 1000ms 内存限制: 65536kB
描述
Determine the columns of N queens should be place on. Columns should be greater than 1 and less than N. Columns should be all different. Each column plus its index should be different from others. Each column minus its index should also be different from others.
输入
One positive integer number N (N <= 200).
输出
An N*N 0/1 matrix A = {a[i][j]}, a[i][j]=1 indicates that there is a queue on cell (i,j), and a[i][j]=0 otherwise.
样例输入
4
样例输出
0 1 0 0
0 0 0 1
1 0 0 0
0 0 1 0
翻译
描述
确定应放置N个皇后的列。列应大于1且小于N。列应各不相同。每一列及其索引都应该与其他列不同。每一列减去其索引也应与其他列不同。
输入
一个正整数N(N<=200)。
输出
N*N 0/1矩阵A={A[i][j]},A[i][j]=1表示单元(i,j)上有队列,否则A[i][j]=0。
代码
#include <bits/stdc++.h>
using namespace std;
const int N=201;
int n;
bool xk[2N],
fxk[2N],
lk[N],
k[N][N];
void view(){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++)cout<<k[i][j]<<" ";cout<<endl;
}
cout<<endl;
}
bool kk;
void go(int h,int m){
if(m==n&&!kk){
view();
kk=1;return;
}
if(!kk)
for(int i=0;i<n;i++){
if(!lk[i]&&!xk[n-1+h-i]&&!fxk[h+i]){
k[h][i]=lk[i]=xk[n-1+h-i]=fxk[h+i]=1;
go(h+1,m+1);
k[h][i]=lk[i]=xk[n-1+h-i]=fxk[h+i]=0;
}
}
}
int main(){
//freopen(“data.cpp”,“r”,stdin);
cin>>n;
go(0,0);
return 0;
}
技术细节
1.关键就是输出第一个。
2.全输出会错
3.输出最后一个也不行。
4.貌似
0 1 0 0
0 0 0 1
1 0 0 0
0 0 1 0
就可以
601

被折叠的 条评论
为什么被折叠?



