EightOfQueen.h
#ifndef EIGHTOFQUEEN_H_INCLUDED #define EIGHTOFQUEEN_H_INCLUDED #include <string> using namespace std; class QueenChess { public: QueenChess(); void Solve(); string chess[8]; int solves; private: bool SafeJudge(int row,int col) const; void PlaceQueen(int row); void DrawChess() const; }; #endif // EIGHTOFQUEEN_H_INCLUDED
EightOfQueen.cpp
#include <iostream> #include "EightOfQueen.h" #include <cstring> using namespace std; void start() { QueenChess Qchess; Qchess.Solve(); } //判断是否安全 bool QueenChess::SafeJudge(int row,int col) const { int qrow,qcol; //只检查与前面的棋子是否安全 for(qrow=0;qrow<row;qrow++) { string row_string = chess[qrow]; qcol = row_string.find("Q"); if(qrow == row || qcol == col || (qcol-qrow) == (col-row) || (qcol+qrow) == (row + col)) { return false; } } return true; } //打印 void QueenChess::DrawChess() const { cout << "\n第" << solves << "个解为:"<< endl; cout << " 1 2 3 4 5 6 7" << endl; for(int i=0;i<8;i++) { cout << i << " "; for(int j=0;j<8;j++) { cout << chess[i][j] << " "; } cout << endl; } } //放置各列的棋子 void QueenChess::PlaceQueen(int row) { for(int col=0;col<8;col++) { if(SafeJudge(row,col)) //是否安全才能放置 { chess[row][col] = 'Q'; if(row < 7) { PlaceQueen(row+1); } else { solves++; DrawChess(); } } //chess[row] = "--------"; } } //给出纺织成功的棋盘总数 void QueenChess::Solve() { PlaceQueen(0); //第0行开始放置 cout << "总共解的个数:" << solves << endl; } //构造函数,初始化棋盘 QueenChess::QueenChess() { solves = 0; for(int i=0;i<8;i++) { chess[i] = "--------"; } } int main() { start(); return 0; }