6
2 4 6 1 3 5
3 6 2 5 1 4
4 1 5 2 6 3
4
#include<cmath> #include<cstdio> #include<cstdlib> #include<cstring> #include<iostream> #include<algorithm> using namespace std;//注意,N皇后 int a[15]; bool b[15],c[30],d[30]; int sum,k=3,N; void print(){ if(k>0){ for(int i=1;i<=N;i++){ cout<<a[i]<<‘ ‘; } cout<<endl; --k; } sum++; } void tryy(int t){ int j; for(j=1;j<=N;j++){ if(b[j]&&c[t+j-1]&&d[t-j+N]){ a[t]=j; b[j]=false; c[t+j-1]=false; d[t-j+N]=false; if(t==N) print(); else tryy(t+1); b[j]=true; c[t+j-1]=true; d[t-j+N]=true; } } } int main(){ memset(b,1,sizeof(b)); memset(c,1,sizeof(c)); memset(d,1,sizeof(d)); // freopen("01.txt","r",stdin); scanf("%d",&N); tryy(1); printf("%d\n",sum); return 0; }
TYVJ P1080 N皇后 Label:dfs PS:以前做的一道题,贴出来防忘
原文:http://www.cnblogs.com/radiumlrb/p/5789566.html