n皇后问题

来源:https://blog.csdn.net/gyhguoge01234/article/details/51039104

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

#include <stdio.h>

int n;
int tot;
int C[20];
int result[20];

void search(int cur)
{
if(cur == n)
tot++;
else
for(int i = 0; i <n; ++i)
{
int ok = 1;
C[cur] = i;
for(int j = 0; j < cur; ++j)
if(C[cur] == C[j] || cur-C[cur] == j-C[j] || cur+C[cur] == j+C[j])
{
ok = 0;
break;
}
if(ok)
search(cur+1);
}
}

int main()
{
for(int i = 1; i <= 11 ; ++i)//一定要打表,否则会超时
{
n = i;
tot = 0;
search(0);
result[i] = tot;
}
while(scanf("%d",&n) && n != 0)
printf("%d\n",result[n]);
return 0;
}