八皇后 n皇后 问题

#include <cstdlib>
#include <vector>
#include <iostream>
using namespace std;
void show(vector<int>& pos)
{
	for(int i = 0; i < pos.size(); ++i)
	{
		cout << pos[i] << '\t';
	}
	cout << endl;
}
bool isValid(vector<int>& pos, int end)
{
	bool flag = true;
	for(int i = 0; i < end; ++i)
	{
		if(pos[i] == pos[end] || abs(i - end) == abs(pos[i] - pos[end]))
		{
			flag = false;
			break;
		}
	}
	return flag;
}
// 回溯法
int nQueen(int n)
{
	if(n < 1)
	{
		return 0;
	}
	int count = 0;
	vector<int> pos(n, -1);
	int level = 0;
	while(level >= 0)
	{
		if(level == n) // 处于最末层
		{
			if(isValid(pos, n - 1))
			{
				++count;
			}
			--level;
			continue;
		}
		pos[level]++;
		if(pos[level] == n) // 当前层以尝试所有位置
		{
			pos[level] = -1;
			--level;
			continue;
		}
		else if(!isValid(pos, level)) // 剪枝
		{
			continue;
		}
		++level;
	}
	return count;
}
void getValidPos(vector<int>& pos, int start, int* count)
{
	if(start == pos.size())
	{
		if(isValid(pos, start - 1))
		{
			++(*count);
		}
		return;
	}
	for(int i = 0; i < pos.size(); ++i)
	{
		pos[start] = i;
		if(isValid(pos, start))
		{
			getValidPos(pos, start + 1, count);
		}
	}
	pos[start] = -1;
	return;
}
// 递归解法
int nQueenRecursive(int n)
{
	if(n < 1)
	{
		return 0;
	}
	int count = 0;
	vector<int> pos(n, -1);
	getValidPos(pos, 0, &count);
	return count;
}
int main(int argc, char* argv[])
{
	cout << "Nonrecursive solution" << endl;
	for(int i = 0; i <= 10; ++i)
	{
		cout << nQueen(i) << endl;
	}
	cout << "Recursive solution" << endl;
	for(int i = 0; i <= 10; ++i)
	{
		cout << nQueenRecursive(i) << endl;
	}
	return 0;
}

运行结果:

Nonrecursive solution
0
1
0
0
2
10
4
40
92
352
724
Recursive solution
0
1
0
0
2
10
4
40
92
352
724

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值