1. 程式人生 > >dfs n皇后問題

dfs n皇后問題

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
int n;
int hang[11];
int sum;

void dfs(int x,int y)
{
	if(x==y)
	{
		sum++;
		return;
	}
	for(int i=0;i<n;i++)
	{
		hang[x] = i;
		bool cherk = true;
		for(int j=0;j<x;j++)
		{
			if(hang[x]==hang[j] || hang[x]-x==hang[j]-j || x+hang[x]==j+hang[j])
			{
				cherk = false;
			}
		}
		if(cherk)
		{
			dfs(x + 1, y);
		}
	}
}
int main()
{
	while(~scanf("%d",&n))
	{
		memset(hang, 0, sizeof(hang));
		if (n == 0) { break; }
		sum = 0;
		dfs(0, n);
		printf("%d\n", sum);
	}
	return 0;
}

//