#include "stdafx.h"
#include "iostream"
using namespace std;
class ChessBoard
{
public:
ChessBoard();
ChessBoard(int);
void findSolutions();
private:
const bool available;
const int squares, norm;
bool *colum, *leftDiagonal, *rightDiagonal;
int *positionInRow, howMany;
void putQueen(int );
void printBoard();
void initializeBoard();
};
void ChessBoard::printBoard()
{
for (int i = 0; i < squares;i ++)
cout<<positionInRow[i]<<" ";
cout<<endl;
}
ChessBoard::ChessBoard():available(true),squares(8),norm(squares-1)
{
initializeBoard();
}
ChessBoard::ChessBoard(int n):available(true),squares(n),norm(squares-1)
{
initializeBoard();
}
void ChessBoard::initializeBoard()
{
register int i;
colum = new bool[squares];
positionInRow = new int[squares];
leftDiagonal = new bool[squares * 2 -1];
rightDiagonal = new bool[squares * 2 -1];
for (i = 0; i < squares;i ++)
positionInRow[i] = -1;
for (i = 0;i < squares;i ++)
colum[i] = available;
for (i = 0; i < squares; i ++)
leftDiagonal[i] = rightDiagonal[i] = available;
howMany = 0;
}
void ChessBoard::putQueen(int row)
{
for (int col = 0; col < squares; col ++)
{
if (colum[col] == available && leftDiagonal[row + col] == available && rightDiagonal[row - col + norm] == available)
{
positionInRow[row] = col;
colum[col] = !available;
leftDiagonal[row + col] = !available;
rightDiagonal[row - col + norm] = !available;
if (row < squares -1)
putQueen(row +1);
else
printBoard();
colum[col] = available;
leftDiagonal[row + col] = available;
rightDiagonal[row -col + norm] = available;
}
}
}
void ChessBoard::findSolutions()
{
putQueen(0);
cout<<howMany<<" solutions found!"<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
ChessBoard queen8;
queen8.findSolutions();
return 0;
}
n皇后问题
最新推荐文章于 2022-12-01 10:22:27 发布