QueenPuzzle-N皇后问题

Posted Archibald Witwicky

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了QueenPuzzle-N皇后问题相关的知识,希望对你有一定的参考价值。

详见-算法之美-p180.

#include <iostream>
#include <memory.h>
#include <conio.h>
#include <stdlib.h>

using namespace std;

/*
92 solution.
* * * * * * * Q
* * * Q * * * *
Q * * * * * * *
* * Q * * * * *
* * * * * Q * *
* Q * * * * * *
* * * * * * Q *
* * * * Q * * *
*/ 

class QueenPuzzle
{
public:
	QueenPuzzle(int _n);

public:
	void printOut();
	void QueenDFS(int _n);
	int IsValidate(int _n);

private:
	int sum;
	int max;
	int * queen;
};

QueenPuzzle::QueenPuzzle(int _n)
{
	this->sum = 0;
	this->max = _n;
	this->queen = new int[this->max]();
}

void QueenPuzzle::printOut()
{
	for(int i = 0; i < this->max; i++)
	{
		for(int j = 0; j < this->max; j++)
		{
			if(j == this->queen[i])
				cout << "Q ";
			else
				cout << "* ";
		}
		cout << endl;
	}
	
	cout << endl << "Enter any key to continue, Q key exit:" << endl << endl;
	if(getch() == ‘q‘) exit(0);
}

void QueenPuzzle::QueenDFS(int _n)
{	
	if(_n == this->max)
	{
		sum++;
		cout << endl << sum << " solution." << endl;
		this->printOut();
		return;
	}

	for(int i = 0; i < this->max; i++)
	{
		this->queen[_n] = i;
		
		if(IsValidate(_n))
		{	
			this->QueenDFS(_n + 1);
		} 
	}
}

int QueenPuzzle::IsValidate(int _n)
{
	for(int i = 0; i < _n; i++)
	{
		if(this->queen[i] == this->queen[_n])
			return 0;
		
		if(abs(this->queen[i] - this->queen[_n]) == (_n - i))
			return 0;
	}
	
	return 1;
}

int main()
{
	QueenPuzzle queen(8);
	queen.QueenDFS(0);
	
	return 0;
} 

  

以上是关于QueenPuzzle-N皇后问题的主要内容,如果未能解决你的问题,请参考以下文章

易理解java代码8皇后问题

八皇后问题求解的C语言程序的实现

八皇后

八皇后,回溯与递归(Python实现)

八皇后

基于WPF的八皇后简单应用程序