n后问题 nQueen(分支限界法,BFS)

本文通过分支限界法(BFS)详细解析了经典的n后问题,介绍了如何在棋盘上放置n个皇后,使得它们互不攻击。代码中包含逻辑注释,便于理解。
摘要由CSDN通过智能技术生成

逻辑注释在代码中
完整代码:

#include<iostream>
#include<queue>
using namespace std;
// 用来判断棋盘上的点(row, column) 是否安全 
bool canPut (int row, int column, int *answer);
int main()
{
	int queens;
//	current表示当前层数,activated表示当前活结点所在的column 
	int activated = 0;
	int current = 0;
	cout << "输入皇后数:";
	cin >> queens;
	if (queens <= 3)
	{
		cout << "no solution!";
		return 0;
	}
//	每一层都有一个队列保存可生成结点 
	queue<int> Queue[queens];
//	棋盘 ,改用answer保存 
//	int chessboard[queens][queens] = {0};
//	answer作为辅助数组,下标表示层级,值表示column ,也就是棋盘 
	int answer[queens] = {-1};
//	第一层肯定全为活结点 
	for (int i = 0; i < queens; i++)
	{
		Queue[0].push(i);
	}
	while (1)
	{
//		当前层级没有安全位置或者回退 
		if (Queue[current].empty())
		{
			current--;
			continue;
		}
//		找不到解(边界问题) 
		if (current == -1)
		{
			cout<< "no solution!";
			break; 
		}
//		取当前层级队列头为活结点并弹出队列 
		activat
  • 0
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值