回溯法:《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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT远征军

谢谢各位鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值