八皇后问题的C++实现

来源:互联网 发布:seo官网站内 编辑:程序博客网 时间:2024/05/16 07:01

 //八皇后问题的实现
#include <iostream>
#include <string>
using namespace std;
//QueenChess类声明
class QueenChess
{
      public:
             QueenChess();         //构造函数
             void Solve();         //求解八皇后问题,并给出放置成功的棋盘总个数
      private:
              string chessState[8];         //用于存放棋盘状态
              int solves;                   //八个皇后放置成功的棋盘解的总个数
              bool SafeJudge(int row,int col) const;    //判断位置(row,col)是否安全
              void PlaceQueen(int row);                 //在第row行放置一个皇后
              void DrawChess() const;                   //打印八个皇后放置成功的棋盘
};

//构造函数,将棋盘初始化
QueenChess::QueenChess()
{
      solves=0;
      int i=0,j=0;
      for(;i<8;++i)
      chessState[i]="--------";
}

//求解八皇后问题,并给出放置成功的棋盘总个数
void QueenChess::Solve()
{
     //从第0行开始放置皇后
     PlaceQueen(0);
     cout<<"/n八皇后问题总共的解的个数是:"<<solves<<endl;
}

//在第row行的各列放置皇后
void QueenChess::PlaceQueen(int row)
{
     //穷尽第row行的所有列
     for(int col=0;col<8;col++)
     {
             if(SafeJudge(row,col))
             {
                     //位置(row,col)安全,则放一皇后
                     chessState[row][col]='Q';
                     //若还没有放到第八行,则尝试下一行
                     if(row<7)
                        PlaceQueen(row+1);
                     //已经放置了八个皇后,打印出成功的棋盘,并将解数加1
                     else
                     {
                         solves++;
                         DrawChess();
                     }
             }//end if
             //不安全,将该处的皇后拿走,尝试下一列位置
             chessState[row]="--------";
     }
}

//判断是否(row,col)是安全位置
bool QueenChess::SafeJudge(int row,int col) const
{
     int qRow,qCol;
     //检查前面各行,看与前面的皇后是否发生攻击
     for(qRow=0;qRow<row;qRow++)
     {
           string rowState=chessState[qRow];
           //寻找第qRow行放置皇后的列数
           qCol=rowState.find("Q");
           //如果两个皇后在同一行、同一列或两条对角线上,则说明该位置不安全
           if(qRow==row||qCol==col||(qCol-qRow)==(col-row)||(qCol+qRow)==(col+row))   
              return false;
     } //end if
     return true;
}

//打印成功的棋盘
void QueenChess::DrawChess() const
{
     int i,j;
     cout<<"/n八皇后问题的第"<<solves<<" 个解为:"<<endl;
     cout<<"  0 1 2 3 4 5 6 7"<<endl;
     for(i=0;i<8;++i)
     {
           cout<<i<<" ";
           for(j=0;j<8;++j)
              cout<<chessState[i][j]<<" ";
           cout<<endl;
     } //end for
     //每打印一个成功的八皇后棋盘,暂停一下
     //system("pause");
}

//main函数进行测试
int main()
{
   QueenChess  chess;
   chess.Solve();
   system("pause");
   return 0; 
  
}

原创粉丝点击