wisdom2010 @ 2024-07-20 21:30:58
#include<bits/stdc++.h>
using namespace std;
int n;
const int maxn = 13 + 5;
int lie[maxn] = {0}, r[maxn] = {0}, l[maxn] = {0};
int dis[maxn];
int ans = 0;
void dfs(int step)
{
if(step == n)
{
ans++;
if(ans <= 3)
for(int i = 0; i < n; i++)
printf("%d ", dis[i] + 1);
if(ans <= 3)
printf("\n");
return ;
}
for(int i = 0; i < n; i++)
{
if(lie[i] != 1 && l[step + i] != 1 && r[step - i + n] != 1)
{
lie[i] = 1;
l[step + i] = 1;
r[step - i + n] = 1;
dis[step] = i;
dfs(step + 1);
lie[i] = 0;
l[step + i] = 0;
r[step - i + n] = 0;
}
}
}
int main()
{
scanf("%d", &n);
dfs(0);
printf("%d", ans);
return 0;
}
为什么n = 13时wa了?
by __1943 @ 2024-07-23 19:02:42
你试下我这个
#include<bits/stdc++.h>
using namespace std;
int n,ans[100],cnt;
bool f1[100],f2[100],f3[100];//列,正对角线,逆对角线
void setFlag(int i,int j,int num)
{
f1[j]=num;
f2[i+j]=num;
f3[i-j+n]=num;
ans[i]=j;//第i行的国王放在j的位置上
}
//往每一行上放皇后
void dfs(int i)
{
if(i>n){
cnt++;
if(cnt<=3)
{
for(int i=1;i<=n;i++) cout<<ans[i]<<' ';
cout<<endl;
return ;
}
}
for(int j=1;j<=n;j++)
{
//标记列,逆对角线,正对角线
if(f1[j]||f2[i+j]||f3[i-j+n]) continue;
setFlag(i,j,1);
dfs(i+1);
setFlag(i,j,0);
}
}
int main(){
cin>>n;
dfs(1);
cout<<cnt;
return 0;
}