用回溯法解决
q[i]表示第i行皇后所在的列下标
#include <iostream>
using namespace std;
void search(int *p , int n , int cur , int* count , int* node){
(*node)++ ;
if(cur == n ){
(*count)++;
cout<<*count<<"th solution:"<<endl ;
for(int i=0 ; i != n ; i++)
cout<<p[i]<<" "<<flush ;
cout<<endl ;
return ;
}
for(int i = 0 ; i != n ; i++){
p[cur] = i ;
int ok = 1 ;
for(int j = 0 ; j != cur ; j++)
if(p[j] == p[cur] || j+p[j] == cur+p[cur] || j-p[j] == cur - p[cur]){
ok = 0 ;
break ;
}
if(ok == 1 )
search( p , n , cur+1,count , node) ;
}
}
int n_queen( int n , int* node ){
int* p = new int[n] ;
int count = 0 ;
int *q = &count ;
search(p , n , 0 , q , node) ;
delete[] p ;
return count ;
}
int main()
{
int n ;
int m ;
int *node = &m ;
cout<<"input n : "<< flush ;
while(cin>>n){
m = 0 ;
if(n<2)
cout<<" n should not less than 2 "<<endl;
else{
cout<<"the count of "<<n<<" queens problem's solution is : "<<n_queen(n ,node )<<endl ;
cout<<"the count of "<<n<<" queens problem's nodes is : "<<m<<endl ;
}
cout<<"input n : "<< flush ;
}
return 0;
}