八皇后和N皇后问题

(1)八皇后与N皇后问题

八皇后问题是一个古老而著名的问题,是回溯算法的典型例题。该问题是十九世纪著名的数学家高斯1850年提出:在8X8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。高斯认为有76种方案。1854年在柏林的象棋杂志上不同的作者发表了40种不同的解,后来有人用图论的方法解出92种结果。


八皇后问题可以推广到n皇后问题:
在n×n格的棋盘上放置彼此不受攻击的n个皇后。按照国际象棋的规则,皇后可以攻击与之处在同一行或同一列或同一斜线上的棋子。n后问题等价于在n×n格的棋盘上放置n个皇后,任何2个皇后不放在同一行或同一列或同一斜线上。

(2)N皇后问题的编程实现

#include<iostream>
using namespace std;
/*
bool isLegal(int *Row,int CurrentColumn)--------判断当前坐标点(Row(CurrentColumn),CurrentColumn)是否符合要求
*/
bool isLegal(int *Row,int CurrentColumn)
{
	for (int column = 1; column < CurrentColumn; column++)
		if ((abs(CurrentColumn - column) == abs(Row[column] - Row[CurrentColumn])) || (Row[column] == Row[CurrentColumn]))return false;
	return true;
}

/*
void Backtrack(int *Row,int n,int CurrentColumn,int &count)--------回溯,遍历排列树
input
	int *Row-------------------行号,其数组元素Row[column]蕴含了棋盘上坐标点(Row[column],column)的行号和列号
	int n----------------------Row的长度,即棋盘的大小为n*n
	int CurrentColumn----------遍历至第CurrentColumn列,即当前列
	int &count-----------------对符合要求的排列进行计数
*/
void Backtrack(int *Row,int n,int CurrentColumn,int &count)
{
	//如果当前所在列CurrentColumn大于n,则计数使(count+1)并输出当前排列结果
	if (CurrentColumn > n)
	{
		count++;
		for (int column = 1; column <= n; column++)cout <<'('<< Row[column]<<','<<column<<')'<< ' ';
		cout << endl;
	}	
	else
		//遍历当前列的每一行,若找到符合要求的点则遍历下一列
		for (int row = 1; row <= n; row++)
		{
			Row[CurrentColumn] = row;
			if(isLegal(Row, CurrentColumn))Backtrack(Row,n,CurrentColumn + 1,count);
		}
			
}

int main()
{
	int n,count=0;
	cin >> n;
	int *Row = new int[n];
	for (int column = 0; column < n; column++)Row[column] = 0;
	Backtrack(Row, n, 1, count);
	cout << count << endl;
	delete []Row;
	return 0;
}

以八皇后问题为例,共有92方案,程序部分运行结果如下所示:
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

tingyuweilou

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值