n皇后问题

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值