留言 | 关于 | 联系
基础数学 语言相关算法实现 其它知识
返回首页
当前位置: 首页 > 程序设计 > 算法实现 > 人工智能学习(2)--八皇后问题

人工智能学习(2)--八皇后问题

时间:2010-03-26 20:51来源:网络 作者:iampolaris 点击:
人工智能学习之八皇后问题,通过八皇后问题对递归算法做出进一步的了解。


下面通过八皇后问题对递归算法做出进一步的了解:

从八皇后的例子看出搜速深度有限,仅有几层,而且不可能出现重复状态的问题,因此BACKTRACK过程完全适用,对于八数码问题则不然,必须设置深度范围限制及出现重复状态引起的死循环这两个回溯点。

下面是八皇后的程序代码:

 

  1. #include <iostream>  
  2.  
  3. using namespace std;  
  4. const int SIDELEN = 8;  
  5. int qunPsn[SIDELEN + 1]; //in order to caculate easily, we start the array from index 1st  
  6. int pRow = 0;  
  7. int count;  
  8. bool Safty(int clnPsn, int Row);  
  9.  
  10. int Abs(int tmp);  
  11.  
  12. int main()  
  13.     pRow = 1;  
  14.  
  15.     /*initialize the array*/  
  16.     for (int i = 0; i < SIDELEN + 1; i ++)  
  17.         qunPsn[i] = 0;  
  18.      
  19.     count = 0;  
  20.      
  21.     do  
  22.     { 
  23.         qunPsn[pRow]++;  
  24.         while(qunPsn[pRow] <= SIDELEN && !Safty(qunPsn[pRow], pRow)) qunPsn[pRow]++;   
  25.          
  26.         if(qunPsn[pRow] <= SIDELEN && pRow == 8) 
  27.             count++;  
  28.          
  29.         else if(qunPsn[pRow] <= SIDELEN && pRow < 8)  
  30.             pRow++;  
  31.          
  32.         else 
  33.             qunPsn[pRow--] = 0;  
  34.          
  35.     }while(pRow);  
  36.      
  37.     cout << "TotalMethod = " << count << endl;  
  38.      
  39.     char tmp;  
  40.     cin >> tmp;  
  41.      
  42.     return 0;  
  43.      
  44. }  
  45.  
  46. bool Safty(int clnPsn, int row)  
  47. {  
  48.      
  49.     for(int i = 1; i < row; i++)  
  50.     {  
  51.         if ( qunPsn[i] == clnPsn || Abs(clnPsn - qunPsn[i]) == Abs(row - i) ) return false;  
  52.     }  
  53.      
  54.     return true;  
  55.      
  56. }  
  57.  
  58. int Abs(int tmp)  
  59. {  
  60.     return (tmp > 0 ? tmp : (0 - tmp));  
  61. }  

 

顶一下
(2)
100%
踩一下
(0)
0%
发表评论
评价:
验证码:点击我更换图片
推荐内容