hdu 2553 n皇后问题

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>

using namespace std;

const int MAXN = 15;

int row[MAXN], sum, n;//row[num] = i,表示第num行皇后放在第i列
int ans[MAXN];


bool Judge(int num)//判断num行,row[num]列之前,是否存在冲突
{
	int i;
	for (i = 1; i < num; ++i)
	{
		if(row[i] == row[num] || (fabs(row[num] - row[i]) == num - i))
			return false;
	}
	return true;
}

void DFS(int num)
{
	int i;
	for (i = 1; i <= n; ++i)//搜索列
	{
		row[num] = i;
		if(Judge(num))
		{
			if(num == n)
				sum++;
			else
				DFS( num + 1 );
		}
	}
	return ;
}

void Pre_Slove()
{
	memset(ans, 0, sizeof(ans));
	int i;
	for (i = 1; i <= 11; ++i)
	{
		sum = 0;
		n = i;
		DFS(1);
		ans[i] = sum;
	}
	return ;
}

int main()
{
	int m;
	Pre_Slove();
	while (~scanf("%d", &m), m)
	{
		printf("%d\n", ans[m]);
	}
	return 0;
}

你可能感兴趣的:(搜索)