这是个经典的算法,我就不多说了。下面的代码不是我原创的,收集一下这些经典算法的实现,供自己和有兴趣的朋友学习学习。
1 #include "stdafx.h"
2 #include <stdlib.h>
3 #include <malloc.h>
4
5 int place(int k, int*x);
6 void queens(int n);
7 void main()
8 {
9 queens(8);
10 system("PAUSE");
11 }
12
13 int place(int k, int*x)
14 {
15 int i;
16 for (i =1; i < k; i ++)
17 {
18 if ((x[i -1] == x[k -1]) | (x[i -1] - x[k -1] == i - k) | (x[i -1] - x[k -1] == k - i))
19 {
20 return-1;
21 }
22 }
23 return1;
24 }
25
26 void queens(int n)
27 {
28 int*x, i, k, cs;
29
30 x = (int*)malloc(n + n);
31 cs =0;
32 x[0] =0;
33 k =1;/*Queen k is place at column x[k-1]*/
34 while(k >0)
35 {
36 /*find a column*/
37 do
38 {
39 x[k -1] = x[k -1] +1;
40 } while (x[k -1] <= n && place(k, x) <0);
41
42 if (x[k -1] <= n)
43 {
44 /*ensure the column we find is valid*/
45 if (k == n)
46 {
47 /*out put a topology*/
48 cs ++;
49 printf("\nS.%3d",cs);
50 for (i =0; i < n; i ++)
51 {
52 printf("%2d",x[i]);
53 }
54 }
55 else
56 {
57 /*继续摆放后续的皇后*/
58 k = k +1;
59 x[k -1] =0;
60 }
61 }
62 else
63 {
64 k = k -1;
65 }
66 }
67 }
2 #include <stdlib.h>
3 #include <malloc.h>
4
5 int place(int k, int*x);
6 void queens(int n);
7 void main()
8 {
9 queens(8);
10 system("PAUSE");
11 }
12
13 int place(int k, int*x)
14 {
15 int i;
16 for (i =1; i < k; i ++)
17 {
18 if ((x[i -1] == x[k -1]) | (x[i -1] - x[k -1] == i - k) | (x[i -1] - x[k -1] == k - i))
19 {
20 return-1;
21 }
22 }
23 return1;
24 }
25
26 void queens(int n)
27 {
28 int*x, i, k, cs;
29
30 x = (int*)malloc(n + n);
31 cs =0;
32 x[0] =0;
33 k =1;/*Queen k is place at column x[k-1]*/
34 while(k >0)
35 {
36 /*find a column*/
37 do
38 {
39 x[k -1] = x[k -1] +1;
40 } while (x[k -1] <= n && place(k, x) <0);
41
42 if (x[k -1] <= n)
43 {
44 /*ensure the column we find is valid*/
45 if (k == n)
46 {
47 /*out put a topology*/
48 cs ++;
49 printf("\nS.%3d",cs);
50 for (i =0; i < n; i ++)
51 {
52 printf("%2d",x[i]);
53 }
54 }
55 else
56 {
57 /*继续摆放后续的皇后*/
58 k = k +1;
59 x[k -1] =0;
60 }
61 }
62 else
63 {
64 k = k -1;
65 }
66 }
67 }
输出:(共92种情况)