递归法解决N皇后问题
前一遍文章有写遗传算法解决N皇后的问题,个人感觉遗传算法的解决方法比较好理解,递归算法初一看挺简单,但让你下一次再写就不一定能写出来。遗传算法看起来难实则容易
1 #include<iostream> 2 #include<string.h> 3 #include<math.h> 4 using namespace std; 5 #define NUM 8 6 int x[NUM]; 7 int queen_num=0; 8 9 bool place(int t ) 10 { 11 for(int i=0;i<t;++i) 12 { 13 if(x[i]==x[t]||(abs(t-i)==abs(x[i]-x[t]))) 14 return false; 15 } 16 17 return true; 18 } 19 void output() 20 { 21 for(int i=0;i<NUM;++i) 22 { 23 cout<<x[i]<<" "; 24 } 25 cout<<endl; 26 ++queen_num; 27 28 } 29 void traceback(int t) 30 { 31 if(t==NUM) 32 { 33 output(); 34 return; 35 } 36 for(int i=0;i<NUM;++i) 37 { 38 x[t]=i; 39 if(place(t)) 40 traceback(t+1); 41 } 42 } 43 44 int main() 45 { 46 memset(x,0,sizeof(x)); 47 traceback(0); 48 cout<<queen_num<<endl; 49 return 0; 50 }

浙公网安备 33010602011771号