回溯法——N皇后问题
#include<bits/stdc++.h>
using namespace std;
const int N = 15;
int g[N][N];
bool col[N],d1[N*2],d2[N*2];
int n;
int ans;
void Print()
{
for(int i = 1;i<=n;i++)
{
for(int j = 1;j<=n;j++)
{
cout<<g[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
void dfs(int r)
{
if(r>n)
{
ans++;
return;
}
for(int i = 1; i <= n; i ++ )
{
if(!col[i] && !d1[n+r+i] && !d2[n+r-i])
{
col[i] = d1[n+r+i] = d2[n+r-i] = true;
g[r][i] = 1;
dfs(r+1);
g[r][i] = 0;
col[i] = d1[n+r+i] = d2[n+r-i] = false;
}
}
}
int main()
{
cin>>n;
memset(g,0,sizeof(g));
ans = 0;
dfs(1);
cout<<ans<<endl;
return 0;
}