c实现的8皇后

Posted on 2012-03-15 23:21  Fredric  阅读(169)  评论(0编辑  收藏  举报

拿C实现了一个8皇后,回溯的算法实现对单一解得获得。棋盘大小超过18个仍然有问题,改天在调试。

去年代码写的太少了,生疏的真快。

View Code
  1 #include <stdio.h>
2 #include <math.h>
3
4
5 #define MAX_NUM (10)
6
7 int col[MAX_NUM] = {0};
8 int status[MAX_NUM][MAX_NUM] = {0};
9
10 void find(int col);
11 void initStatus(int col);
12 int findcol(int col);
13 int isGood(int col, int rum);
14 void showTable();
15
16 void main(){
17
18 find(0);
19
20 showTable();
21
22 return;
23 }
24
25 //寻找第col列的解
26 void find(int col){
27
28
29 if (1 == findcol(col))
30 {
31 if (MAX_NUM - 1 != col)
32 {
33 find(col + 1);
34 }
35 else
36 {
37 return;
38 }
39
40 }else{
41 initStatus(col);
42 find(col - 1);
43 }
44 }
45
46 void initStatus(int col)
47 {
48 for (int i = 0; i < MAX_NUM; i++)
49 {
50 status[col][i] = 0;
51 }
52 }
53
54 /*
55 * 在当前第col列可以找到位置
56 * res:在第col列所放置的位置
57 */
58 int findcol(int icol)
59 {
60 for (int i = 0; i < MAX_NUM; i++)
61 {
62 if (0 == status[icol][i])
63 {
64 if (1 == isGood(icol, i))
65 {
66 status[icol][i] = 1;
67 col[icol] = i;
68
69 return 1;
70 }
71 }
72 }
73
74 return -1;
75 }
76
77 int isGood(int icol, int rum)
78 {
79 for (int i = 0; i < icol; i++)
80 {
81 if((col[i] == rum)
82 ||(abs(col[i] - rum) == abs(i - icol))){
83
84 return -1;
85 }
86 }
87
88 return 1;
89 }
90
91 //打印结果
92 void showTable(){
93
94 for (int i = 0; i < MAX_NUM; i++)
95 {
96 for (int j = 0; j < MAX_NUM; j++)
97 {
98 if (col[i] == j)
99 {
100 printf("%c ", '*');
101 }
102 else
103 {
104 printf("%d ", 0);
105 }
106 }
107
108 printf("\r\n");
109 }
110
111 return;
112 }



Copyright © 2024 Fredric
Powered by .NET 8.0 on Kubernetes