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 <iostream>
#include <iomanip>
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <string>
using namespace std;
int a[15],b[15],tot;
void dfs(int cur,int n)
{
	if(cur==n)
		tot++;
	else 
	{
		for(int i=0;i<n;i++)
		{
			a[cur]=i;
			int ok=1;
			for(int j=0;j<cur;j++)
			{
				if(a[cur]==a[j]||cur-a[cur]==j-a[j]||cur+a[cur]==j+a[j])
				{
					ok=0;
					break;
				}
			}
			if(ok) 
			dfs(cur+1,n);
		}
	}
}
int main()
{
	for(int i=1;i<=10;i++)
	{
		tot=0;
		dfs(0,i);
		b[i]=tot;
	}
	int m;
	while(cin>>m&&m)
	{
		cout<<b[m]<<endl;
	}
	return 0;
} 


posted @ 2016-03-06 13:29  (慎独)  阅读(193)  评论(0编辑  收藏  举报