xjx199 @ 2024-01-16 09:20:10
#include<bits/stdc++.h>
using namespace std;
int sum,n;
int a[1000001],b[1000001],c[100001],d[1000001];
void print()
{
sum++;
for(int i=1;i<=n;i++)
{
cout<<a[i];
if(i==n) cout<<endl;
else cout<<" ";
}
}
int dfs(int k)
{
for(int i=1;i<=n;i++)
{
if(b[i]==0 && d[k-i+15]==0 && c[k+i]==0)
{
a[k]=i;
b[i]=1;
c[i+k]=1;
d[k-i+15]=1;
if(i==n)
{
print();
}
else dfs(k+1);
b[i]=0;
c[k+i]=0;
d[k-i+15]=0;
}
}
}
int main()
{
int n;
cin>>n;
dfs(1);
cout<<sum<<endl;
return 0;
}
by wanghu @ 2024-02-02 10:58:16
@xjx199
#include<bits/stdc++.h>
using namespace std;
int sum,n;
int a[1001][1001],b[1000001],c[100001],d[1000001];//我习惯用二维数组,好输出
void print(){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(a[i][j]==1){
cout<<j<<" ";
}
}
//cout<<endl;
}
cout<<endl;
}
void dfs(int k){
if(k>n){
sum++;//不能边输出边计数,因为只输出前3个答案
if(sum<=3){
print();
}
return;
}
for(int i=1;i<=n;i++){
if(b[i]==0 && d[k-i+n]==0 && c[k+i]==0){
a[k][i]=1;
b[i]=1;
c[i+k]=1;
d[k-i+n]=1;
dfs(k+1);
b[i]=0;
c[k+i]=0;
d[k-i+n]=0;
a[k][i]=0;
//你没有给a数组归0
}
}
return;
}
int main()
{
cin>>n;
dfs(1);
cout<<sum<<endl;
return 0;
}