Problem Description
Problem Analysis
The N-Queens problem is a classic backtracking problem.
Here we refer to Introduction to Algorithm Competition Classic.
In the dfs, record how many pieces have already been placed.
If the count reaches N, then one complete solution is found.
So the recursion proceeds in exactly this way.
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
| #include<stdio.h>
int res[15];
int flag[15];
int cnt;
int abs(int m) {
return m>0?m:-m;
}
void f(int m,int N) {
if(m==N)
cnt++;
else {
for(int i=0; i<N; i++) {
flag[m]=i;
int j;
for(j=0; j<m; j++)
if(flag[m]==flag[j]||abs(flag[m]-flag[j])==abs(m-j))
break;
if(j==m)
f(m+1,N);
}
}
}
void get() {
for(int i=1; i<=10; i++) {
cnt=0;
f(0,i);
res[i]=cnt;
}
return ;
}
int main() {
get();
int n;
while(scanf("%d",&n),n)
printf("%d\n",res[n]);
return 0;
}
|