回溯法:《8皇后问题》-C++实现

#include "stdio.h"
#include "iostream"
#include "string"
using namespace std;

int count = 0;

int notdanger(int chess[8][8], int d_row, int d_col)
{
	int flag1 = 0, flag2 = 0, flag3 = 0, flag4 = 0, flag5 = 0, flag = 0, flag6 = 0;

	for(int kk = 0; kk < 8; kk ++)
	{
		if(chess[kk][d_col] == 1)
		{
			flag = 1;
			break;
		}
	}

	for(int kk = d_row, jj = d_col; kk >= 0 && jj >=0; kk --, jj --)
	{
		if(chess[kk][jj] == 1)
		{
			flag1 = 1;
			break;
		}
	}

	for(int kk = d_row, jj = d_col; kk < 8 && jj < 8; kk ++, jj ++)
	{
		if(chess[kk][jj] == 1)
		{
			flag2 = 1;
			break;
		}
	}

	for(int kk = d_row, jj = d_col; kk >= 0 && jj < 8; kk --, jj ++)
	{
		if(chess[kk][jj] == 1)
		{
			flag3 = 1;
			break;
		}
	}

	for(int kk = d_row, jj = d_col; kk < 8 && jj >= 0; kk ++, jj --)
	{
		if(chess[kk][jj] == 1)
		{
			flag4 = 1;
			break;
		}
	}

	if(flag1 || flag2 || flag3 || flag4 || flag)
	{
		flag6 = 1;
	}
	else
		flag6 = 0;

	return flag6;
}

void eightqueen(int chess[8][8], int n, int row)
{
	int chess2[8][8];

	for(int i = 0; i < n; i ++)
	{
		for(int j = 0; j < n; j++)
		{
			chess2[i][j] = chess[i][j];
		}
	}

	if(row == 8)
	{
		/*cout << "第" << count + 1 << "种放置:" << endl;
		cout << endl;

		for(int i = 0; i < 8; i ++)
		{
			for(int j = 0; j < 8; j++)
			{
				cout << chess2[i][j] << ' ';
			}
			cout << endl;
		}
		count = count + 1;
		cout << endl;
		cout << endl;*/

		if(count == 0)
		{
			for(int i = 0; i < 8; i ++)
		    {
			    for(int j = 0; j < 8; j++)
			    {
				    cout << chess2[i][j] << ' ';
			    }
			    cout << endl;
		    }
		}
		count = count + 1;
	}
	else
	{
		for(int ii = 0; ii < 8; ii ++)
		{
			if(!notdanger(chess, row, ii))
			{
				for(int j = 0; j < 8; j ++)
				{
					chess2[row][j] = 0;
				}
				chess2[row][ii] = 1;
				eightqueen(chess2, 8, row + 1);
			}
		}
	}
}

int main()
{
	int chess[8][8];

	for(int i = 0; i < 8; i ++)
	{
		for(int j = 0; j < 8; j++)
		{
			chess[i][j] = 0;
		}
	}

	eightqueen(chess, 8, 0);

	system("pause");
	return 0;
}

 

你可能感兴趣的:(回溯法:《8皇后问题》-C++实现)