n皇后问题

n皇后问题

问题描述:
N皇后问题是一个经典的问题,在一个N*N的棋盘上放置N个皇后,每行一个并使其不能互相攻击(同一行、同一列、同一斜线上的皇后都会自动攻击)。
输入皇后数n,输出解,并且打印出n个皇后的坐标。

// Queen.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include<stdlib.h>

template<class Type>
class Queen
{
public:
	Queen(Type*, Type);
	template<class Ty>
	friend  void nQueen(Ty *,Ty);
	void Backtrack(void);
private:
	bool Place(Type n);
	void Backtrack(Type t);
	Type* x,//x是这个当前解
		n;
};

template<class Type>
void Queen<Type>::Backtrack(Type t)//这是递归的解法
{
	if (t > n)
	{
		for (int i = 1; i <= n; i++)
			std::cout << x[i] << "\t";
		std::cout << std::endl;
	}
	else
	{
		for (int i = 1; i <= n; i++)
		{
			x[t] = i;
			if (Place(t))//判断t保存的值是不是能不能被使用
			{
				Backtrack(t + 1);
			}

		}
	}
}

template<class Type>
bool Queen<Type>::Place(Type n)
{
	for (int i = 1; i < n; i++)
	{
		if ((x[n] == x[i]) || abs(x[n] - x[i]) == abs(n - i))
			return false;
	}
	return true;
}

template<class Ty>
void nQueen(Ty* x, Ty n)
{
	Queen<Ty> queen;
	queen.x = x;
	queen.n = n;
	

	queen.Backtrack(1);
}

template<class Type>
void Queen<Type>::Backtrack(void)//迭代递归法
{
	int t = 1;
	x[1] = 0;
	while (t>0)
	{
		x[t] += 1;
		while (x[t]<=n&&!(Place(t)))//寻找x[t]符合的数
			x[t] += 1;
			if (x[t] <= n)//当x[t]小于n时
			{
				if (t == n)
				{
					for (int i = 1; i <= n; i++)
						std::cout << x[i] << "\t";
					std::cout << std::endl;
				}
				else
				{
					t++;
					x[t] = 0;
				}
			}
			else
			{
				t--;
			}
	}
}

template<class Type>
Queen<Type>::Queen(Type* x, Type n)
{
	this->x = x;
	this->n = n;
}

int main()
{

	int *x;
	int n=8;
	x = new int[9];
	Queen<int>* queen = new Queen<int>(x, n);
	queen->Backtrack();
	//nQueen<int>(x,n);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值