peterJr @ 2024-03-27 19:26:27
#include <cstdio>
using namespace std;
int n, col[17], dia1[17], dia2[17], a[17], tot;
inline int print()
{
if (++tot > 3) return EOF;
for (int i = 1; i <= n; ++i)
cout << a[i] << " ";
cout << endl;
return 0;
}
void dfs(int k)
{
if (k > n)
{
print();
}
for (int i = 1; i <= n; ++i)
{
if (!col[i] && !dia1[k + i] && !dia2[k - i + n])
{
col[i] = 1;
dia1[k + i] = 1;
dia2[k - i + n] = 1;
a[k] = i;
dfs(k + 1);
a[k] = 0;
col[i] = 0;
dia1[k + i] = 0;
dia2[k - i + n] = 0;
}
}
}
int main()
{
cin >> n;
dfs(1);
cout << tot << endl;
return 0;
}
by peterJr @ 2024-03-27 19:40:35
用 dfs
怎么错了???
by jydz @ 2024-04-08 13:29:32
@peterJr
#include<bits/stdc++.h>
using namespace std;
int n;
bool v[15];
int a[15];
bool b[30],c[30];
int ans=0;
void dfs(int x)
{
if (x>n)
{
ans++;
if (ans<=3)
{
for (int i=1;i<=n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
}
else
{
for (int i=1;i<=n;i++)
{
if (v[i] && b[i+x] && c[i-x+n])
{
a[x]=i;
v[i]=false;
b[i+x]=false;
c[i-x+n]=false;
dfs(x+1);
v[i]=true;
b[i+x]=true;
c[i-x+n]=true;
}
}
}
}
int main()
{
cin>>n;
memset(v,true,sizeof(v));
memset(a,0,sizeof(a));
memset(b,true,sizeof(b));
memset(c,true,sizeof(c));
dfs(1);
cout<<ans;
return 0;
}