1 #include<iostream> 2 #include<cmath> 3 using namespace std; 4 5 bool check(int row,int *a) 6 { 7 for(int i=0;i<row;i++) 8 if (a[i]==a[row] || fabs(a[i]-a[row])==fabs(i-row)) 9 return false; 10 return true; 11 } 12 13 void show(int *a,int num,int k) 14 { 15 cout<<"the %d answer is:"; 16 cout<<num<<endl; 17 cout<<"-------------------"<<endl; 18 for(int i=0;i<k;i++) 19 for(int j=0;j<k;j++) 20 { 21 if (a[i]==j) 22 cout<<‘*‘; 23 else cout<<‘o‘; 24 if ((j+1)%k==0) 25 cout<<endl; 26 } 27 } 28 void findpos(int row,int *a,int &num,int k) 29 { 30 if(row==k) 31 { 32 num+=1; 33 show(a,num,k); 34 } 35 else{ 36 for(int i=0;i<k;i++) 37 { 38 a[row]=i; 39 if(check(row,a)) 40 findpos(row+1,a,num,k); 41 } 42 } 43 } 44 int main(void) 45 { 46 int a[100]={0};//记录每行的皇后放哪一列 47 int k; 48 cout<<"the number of que is:"; 49 cin>>k; 50 int num=0; 51 findpos(0,a,num,k); 52 system("pause"); 53 return 0; 54 } 55 56 57
原文:http://www.cnblogs.com/fkissx/p/4461798.html