N皇后问题

N皇后问题求解
本文介绍了一个使用回溯算法解决N皇后问题的C++程序实现。该程序通过递归搜索来寻找所有可能的解决方案,并输出每种解决方案的具体棋盘布局。测试用例展示了不同规模的N皇后问题解的数量。
#include<iostream>
#include<cstdio>
#include<cstdlib>

using namespace std;

int search(int);
int print();

int n,sum = 0;
int f[1001],b[1001] = {0},c[2002] = {0},d[2002] = {0};
int main(){
	cin>>n;
	search(1);
	system("pause");
}

int search(int t){
	int i;
	for(i = 1; i <= n; i++){
		if((!b[i])&&(!c[t+i])&&(!d[t-i+n-1])){
			f[t] = i;
			b[i] = 1;
			c[t+i] = 1;
			d[t-i+n-1] = 1;
			if(t == n){
				print();
			}else{
				search(t+1);
			}
			b[i] = 0;
			c[t+i] = 0;
			d[t-i+n-1] = 0;
		}
	}
}

int print(){
	cout<<"<"<<++sum<<">:"<<endl;
	for(int i = 1; i <= n; i++){
		for(int j = 1; j < f[i]; j++) cout<<".";
		cout<<"x";
		for(int j = f[i]+1; j <= n; j++) cout<<".";
		cout<<endl;
	}
}

<P>n       solution(n)  <BR>
1       1  
2       0  
3       0  
4       2  
5       10  
6       4  
7       40  
8       92  
9       352  
10      724  
11      2680  
12      14200  
13      73712  
14      365596  
15      2279184  
16      14772512  
17      95815104  
18      666090624  
19      4968057848  
20      39029188884  
21      314666222712 
22      2691008701644 
23      24233937684440  
24      227514171973736  
25      2207893435808352  
</P>
<P>以上结果可以作为测试案例验证程序。</P>              
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值