人工智能学习(2)--八皇后问题
时间:2010-03-26 20:51来源:网络 作者:iampolaris 点击:次
人工智能学习之八皇后问题,通过八皇后问题对递归算法做出进一步的了解。
下面通过八皇后问题对递归算法做出进一步的了解:
从八皇后的例子看出搜速深度有限,仅有几层,而且不可能出现重复状态的问题,因此BACKTRACK过程完全适用,对于八数码问题则不然,必须设置深度范围限制及出现重复状态引起的死循环这两个回溯点。
下面是八皇后的程序代码:
- #include <iostream>
-
- using namespace std;
- const int SIDELEN = 8;
- int qunPsn[SIDELEN + 1];
- int pRow = 0;
- int count;
- bool Safty(int clnPsn, int Row);
-
- int Abs(int tmp);
-
- int main()
- {
- pRow = 1;
-
-
- for (int i = 0; i < SIDELEN + 1; i ++)
- qunPsn[i] = 0;
-
- count = 0;
-
- do
- {
- qunPsn[pRow]++;
- while(qunPsn[pRow] <= SIDELEN && !Safty(qunPsn[pRow], pRow)) qunPsn[pRow]++;
-
- if(qunPsn[pRow] <= SIDELEN && pRow == 8)
- count++;
-
- else if(qunPsn[pRow] <= SIDELEN && pRow < 8)
- pRow++;
-
- else
- qunPsn[pRow--] = 0;
-
- }while(pRow);
-
- cout << "TotalMethod = " << count << endl;
-
- char tmp;
- cin >> tmp;
-
- return 0;
-
- }
-
- bool Safty(int clnPsn, int row)
- {
-
- for(int i = 1; i < row; i++)
- {
- if ( qunPsn[i] == clnPsn || Abs(clnPsn - qunPsn[i]) == Abs(row - i) ) return false;
- }
-
- return true;
-
- }
-
- int Abs(int tmp)
- {
- return (tmp > 0 ? tmp : (0 - tmp));
- }
|