~cpp 
#include <iostream.h>
#include <math.h>

bool EightQueens(int level, int queens[]);
bool Promissing(int level, int queens[]);
bool WellPutted(int level1, int level2, int queens[]);

int main(int argc, char* argv[])
{
	int queens[8],i;
	for (i=0;i<8;i++) queens[i]=0;

	if (EightQueens(0,queens))
	{
		cout<<"the result is ";
		for (i=0;i<8;i++) 
			cout<<queens[i]<<" ";
		cout<<endl;
	}
	else 
	{
		cout<<"it's an impossible problem\n";
	}
	return 0;
}

bool EightQueens(int level, int queens[])
{
	int i;
	
	for (i=0;i<8;i++)
	{
		queens[level]=i;
		if (Promissing(level,queens))
		{
			if (level==7) 
			{
				return true;
			}
			else 
			{
				if (EightQueens(level+1,queens))
					return true;
			}
		}
	}
	return false;
}

bool Promissing(int level, int queens[])
{
	int i,j;
	if (level==0) 
		return true;
	for (i=0;i<level;i++)
	{
		//for (j=i+1;j<level+1;j++)
		//{
			if (!WellPutted(i,level,queens)) //if (!WellPutted(i,j,queens))
				return false;
		//}
	}	
	return true;
}

bool WellPutted(int level1, int level2, int queens[])
{	
	if (queens[level1]==queens[level2]) 
		return false;
	if (abs(queens[level1]-queens[level2])==abs(level2 - level1)) 
		return false;
	return true;
}


주석처리된 부분은 도전한 이후에 다시 코드를 보았을때 불필요하다고 생각되는 부분을 지운 것입니다. --이덕준
Retrieved from http://wiki.zeropage.org/wiki.php/EightQueenProblem/이덕준소스
last modified 2021-02-07 05:23:11