n皇后问题(回溯)

在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。 
你的任务是,对于给定的N,求出有多少种合法的放置方法。 
 

Input

共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。

Output

共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。

Sample Input

1
8
5
0

Sample Output

1
92
10

代码书上的会超时,打表即可;

打表代码;

#include<stdio.h>
#include<string.h>
#include<math.h>
int tot,c[1000];
int n;
void search(int cur)
{
	int i,j;
	if(cur==n)
	   tot++;
	else
	for(i=0;i<n;i++)
	{
		int find=1;
		c[cur]=i;
		for(j=0;j<cur;j++)
		if(c[cur]==c[j] || abs(cur-j)==abs(c[cur]-c[j]))
		{
			find=0;
			break;
		}
		if(find==1)
		search(cur+1); 
	}
}
int main()
{
	int m,i,j,k;
	n=0;
	while(n<=11)
	{
		tot=0;
		memset(c,0,sizeof(c)); 
		search(0);
		printf("%d\n",tot);
		n++;
	}
	return 0;
}

Ac代码:

#include<stdio.h>
int a[]={1,1,0,0,2,10,4,40,92,352,724,2680};
int main()
{
	int n; 
	while(scanf("%d",&n),n!=0)
	printf("%d\n",a[n]);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44584292/article/details/99984512
今日推荐