C++解八皇后问题

C++解八皇后问题

引用:

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


下面是我给出的C++解法:


#include<iostream>
#include<iomanip>
#include<fstream>
#define eqa(x) x+eq[x] 
#define eqb(x) x-eq[x] 

void eqpermute(int[]);
void eqpermute(int[],int,int);
void eqshow(int[]);
void eqswap(int[],int,int);
bool eqcheck(int[]);
int count=0;
std::ofstream outfile("D:\\eight-queen.txt",std::ios::trunc);

int main(){
	int eq[8]={0,1,2,3,4,5,6,7};
	eqpermute(eq);
	system("pause");
}
void eqpermute(int eq[]){
	eqpermute(eq, 0, 7);
}
void eqpermute(int eq[], int low, int high){	//Permute all the permutations.(Recursion)
	if(low==high){
		//std::cout<<eq[0]<<eq[1]<<eq[2]<<eq[3]<<eq[4]<<eq[5]<<eq[6]<<eq[7]<<std::ends;
		if(eqcheck(eq))
			eqshow(eq);
	}
	else{
		for(int i=low; i<=high ;i++){
			eqswap(eq, low, i);
			eqpermute(eq, low+1, high);
			eqswap(eq, low, i);
		}
	}
}
void eqshow(int eq[]){
	using namespace std;
	outfile<<"EIGHT QUEEN "<<setfill('0')<<setw(4)<<++count<<endl;
	for(int i=0;i<8;++i){
		for(int j=0;j<eq[i];++j)
			outfile<<"□";
		outfile<<"■";
		for(int j=eq[i]+1;j<8;++j)
			outfile<<"□";
		outfile<<endl;
	}
}

void eqswap(int eq[],int a,int b){
	int temp = eq[a];
	eq[a] = eq[b];
	eq[b] = temp;
}

bool eqcheck(int eq[]){
	int a[] = {eqa(0),eqa(1),eqa(2),eqa(3),eqa(4),eqa(5),eqa(6),eqa(7)};
	int b[] = {eqb(0),eqb(1),eqb(2),eqb(3),eqb(4),eqb(5),eqb(6),eqb(7)};
	bool isOK = true;
	for(int i=0;i<7;++i)
		for(int j=i+1;j<8;++j)
			if(a[i]==a[j])
				isOK = false;
	for(int i=0;i<7;++i)
		for(int j=i+1;j<8;++j)
			if(b[i]==b[j])
				isOK = false;
	return isOK;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值