8皇后-----回溯法C++編程練習,皇后-----
/* * 八皇后問題回溯法編程練習 * 在8×8的棋盤上,放置8個皇后,兩個皇后之間不能兩兩攻擊 * 也即,直線,垂直45度、135度方向不能出現兩個皇后 * * copyright Michael 2014-12-19 * QQ 1192065414 **/#include <iostream>#include <stack>#include <stdlib.h>#include <string.h>using namespace std;struct Sposition{ int iRow; int iColumn;};/* * 儲存結果使用的棧 **/stack<Sposition> ResultStack;/* * 判斷在水平方向x,垂直方向y,是否可以放置新皇后 **/bool JudgeIsAcceptable(int x ,int y){ struct Sposition pos; stack<Sposition> resultS(ResultStack); int stackSize = resultS.size(); for ( ; stackSize > 0 ; --stackSize ) { pos = resultS.top(); if( pos.iRow == x ) //判斷同一直線上是否已經有皇后 { return false; } if( (x-pos.iRow) == (y-pos.iColumn) ) //判斷45度角是否已經有皇后 { return false; } if( (x-pos.iRow) == (pos.iColumn-y) ) //判斷-45度角是否已經有皇后 { return false; } resultS.pop(); } return true;}/* * 皇后放置演算法 * 0 0 0... * 0 0 0... * 0 0 0... * ...... * 遍曆第0列,取第0列的第一個、第二個... * 從第1列開始嘗試,然後嘗試第2列,當嘗試到一列,8行都不能放置皇后,則回溯,返回前一列的下一行繼續嘗試 **/void SolveQueue(){ Sposition pos; for (int i = 0 ; i < 8 ; ++i ) { //The first line of the queue pos.iRow = i; pos.iColumn = 0; ResultStack.push(pos); int x = 0; //標記當前行,0~7行 int y = 1; //標記當前列,0~7列 while( y<8 ) //從第一列開始 { for ( ; x < 8 ; ++x ) //從第0行開始探索 { if ( JudgeIsAcceptable(x,y) ) { pos.iRow = x; pos.iColumn = y; ResultStack.push(pos); //放置完成,輸出結果 if ( 8 == ResultStack.size() ) { while ( !ResultStack.empty() ) { pos = ResultStack.top(); cout<<pos.iRow<<"\t"<<pos.iColumn<<endl; ResultStack.pop(); } } x = 0; //這一列放置完成,繼續下一列放置 break; } } if ( 8 == x ) //這一列,8行都不能放置皇后,回溯到上一列的下一行 { pos = ResultStack.top(); x = pos.iRow+1; if ( 8 <= x ) { y = y-2; //如果上一列放置的地方已經是最後一列,則無需繼續嘗試,應該回溯兩列,從前兩列繼續嘗試 ResultStack.pop(); pos = ResultStack.top(); x = pos.iRow+1; } else { --y; //回溯到前一列的下一行繼續嘗試 } ResultStack.pop(); continue; //控制列數,不進行 ++y 操作 } ++y;; } if ( (8 == y) && (ResultStack.size() != 8) ) //如果8行已經嘗試完,但是放置不夠8行,出錯狀態,處理下一種可能性 { while ( !ResultStack.empty() ) { ResultStack.pop(); } } cout<<endl; cout<<endl; }}int main(){ SolveQueue();}