八皇后问题精炼代码

#include<iostream>

#include<math.h>

#include<ctype.h>

using namespace std;

int num=0;

void queen(int n)

int j,i,k,*p;

 p=new int[n]; 

for(i=0;i<n;i++)//初始化 

 p[i]=0; i=0; 

   cout<<endl; 

   cout<<"the "<<n<<" queen problem all result:"<<endl;

 while(1) 

{  if(p[i]<n)//有皇后可调整 

    {   k=0;   

           while((k<i)&&((p[k]-p[i])&&(fabs(p[k]-p[i])-fabs(k-i)))!=0)    

             k=k+1;  

               if(k<i)          

                     p[i]=p[i]+1;  

               else   

                     {   

                           if(i==n-1)    

                                  {    

                                         num++; 

                                               for(j=0;j<n;j++)   

                                                     cout<<(p[j]+1);     

                                                        if(num%4!=0)        cout<<"    ";      

                                                          if(num%4==0)        cout<<endl;      

                                                       p[n-1]=p[n-1]+1;  

                                    }   

                           else    

                                 i=i+1;   

                      }    

               }  

              else            

                 {    

                      p[i]=0;    i=i-1;    

                         if(i<0)   

                                  {     cout<<endl;     delete []p;     break;    }   

                           p[i]=p[i]+1;

               }  

         }

       }

int main()

      int n;

      char c;

       do

            { 

                 cout<<"请输入多少皇后问题:"; 

                cin>>n;  

                 queen(n); 

                  cout<<"一共有几种:"<<num<<endl; 

                  num=0;    

                  cout<<"是否要查第n皇后?是就:y  否就: n"<<endl; 

                 }while(cin>>c,tolower(c)!='n');

        return 0;

}

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页