用C++實現的八皇后問題


我是一個C++初學者,控制台實現了一個八皇后問題。

代碼如下:

//"八皇后問題"V1.0
//李國良於2017年1月11日編寫完成

#include <iostream>
#include <Windows.h>

using namespace std;
const int ArSize = 8;//這個數等於幾,就是幾皇后。
int num = 0;
void solve(bool arr[ArSize][ArSize], int row);
bool check(bool arr[ArSize][ArSize], int row, int column);
void outPut(bool arr[ArSize][ArSize]);

int main()
{
	SetConsoleTitle("八皇后問題");
	bool chessboard[ArSize][ArSize];
	for (auto &i : chessboard)
	{
		for (auto &j : i)
		{
			j = false;
		}
	}
	solve(chessboard, 0);
	cout << "八皇后問題共有" << num << "種解!" << endl;
	system("pause");
	return 0;
}

void solve(bool arr[ArSize][ArSize], int row)
{
	for (int column = 0; column < ArSize; ++column)
	{
		arr[row][column] = true;
		if (check(arr, row, column))
		{
			if (row + 1 == ArSize)
			{
				outPut(arr);
			}
			else
			{
				solve(arr, row + 1);
			}
		}
		arr[row][column] = false;
	}
}

bool check(bool arr[ArSize][ArSize], int row, int column)
{
	if (row == 0)
	{
		return true;
	}
	int i, j;
	for (i = 0; i < row; ++i)
	{
		if (arr[i][column])
		{
			return false;
		}
	}
	i = row - 1;
	j = column - 1;
	while (i >= 0 && j >= 0)
	{
		if (arr[i][j])
		{
			return false;
		}
		--i;
		--j;
	}
	i = row - 1;
	j = column + 1;
	while (i >= 0 && j <= ArSize - 1)
	{
		if (arr[i][j])
		{
			return false;
		}
		--i;
		++j;
	}
	return true;
}

void outPut(bool arr[ArSize][ArSize])
{
	++num;
	cout << "**********************" << num << "*********************" << endl;
	for (int i = 0; i < ArSize; ++i)
	{
		for (int j = 0; j < ArSize; ++j)
		{
			cout << arr[i][j] << " ";
		}
		cout << endl;
	}
	cout << "*********************************************" << endl;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM