xingchen666 @ 2023-07-19 17:48:58
代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 100;
int n;
int a[N];
int b[N];
int c[N];
int d[N];
int total=0;
void dfs(int i){
if(i>n){
total++;
if(total<=3){
for(int k=1;k<=n;k++){
cout<<a[k]<<' ';
}
cout<<endl;
}
return;
}
for(int j=1;j<=n;j++){
if(b[j]==0 && c[i+j]==0 && d[i-j+2*n]==0){
a[i] = j;
b[j] = 1;
c[i+j] = 1;
d[i-j+2*n] = 1;
dfs(i+1);
b[i] = 0;
c[i+j] = 0;
d[i-j+n] = 0;
}
}
}
int main(){
cin>>n;
dfs(1);
cout<<total;
return 0;
}
感觉没错误,各位dalao帮忙看一下谢
by wanglexi @ 2023-08-05 11:38:58
34行b[i]
应该和上面一样是b[j]
,36行d[i-j+n]
也应该和上面一样是d[i-j+2*n]
。
AC代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 100;
int n;
int a[N];
int b[N];
int c[N];
int d[N];
int total=0;
void dfs(int i){
if(i>n){
total++;
if(total<=3){
for(int k=1;k<=n;k++){
cout<<a[k]<<' ';
}
cout<<endl;
}
return;
}
for(int j=1;j<=n;j++){
if(b[j]==0 && c[i+j]==0 && d[i-j+2*n]==0){
a[i] = j;
b[j] = 1;
c[i+j] = 1;
d[i-j+2*n] = 1;
dfs(i+1);
b[j] = 0;
c[i+j] = 0;
d[i-j+2*n] = 0;
}
}
}
int main(){
cin>>n;
dfs(1);
cout<<total;
return 0;
}
by wanglexi @ 2023-08-05 11:56:01
以后,可以复制上面的
b[j] = 1;
c[i+j] = 1;
d[i-j+2*n] = 1;
改所赋的值
b[j] = 0;
c[i+j] = 0;
d[i-j+2*n] = 0;
这样可以一定程度上减少出类似的错