八皇后问题 迭代算法 C++实现

#include 
#include 

#define CHESS_SIZE 8
using namespace std;

int count = 0;

bool checkChess(int row, int col, vector> _chess)
{
	for (int i = 0; i < row; ++i)
	{
		for (int j = 0; j < CHESS_SIZE; ++j)
		{
			if (((abs(i - row) == abs(j - col)) || (j == col)) && 1 == _chess[i][j])
				return 0;
		}
	}
	return true;
}

void displayChess(vector> &chess)
{
	cout << "方案" << ++::count << endl;
	for (int i = 0; i < chess.size(); ++i)
	{
		for (int j = 0; j < chess[i].size(); ++j)
		{
			cout << chess[i][j] << " ";
		}
		cout << endl << endl;
	}
}

void eight_queen(int row, vector> &_chess)
{
	if (row == CHESS_SIZE)
		displayChess(_chess);
	else
	{
		for (int i = 0; i < CHESS_SIZE; ++i)
		{
			_chess[row][i] = 1;
			if (checkChess(row, i, _chess))
				eight_queen(row + 1, _chess);
			_chess[row][i] = 0;
		}
	}
}

int main()
{
	int row = CHESS_SIZE;
	int col = CHESS_SIZE;
	vector> chess(CHESS_SIZE,vector(CHESS_SIZE,0));
	eight_queen(0, chess);
	return 0;
}

 

你可能感兴趣的:(八皇后问题 迭代算法 C++实现)