File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1- #include < stdio.h>
1+ #include < stdio.h>
2+ #include < math.h>
23
4+ /* 八皇后问题是在8*8的棋盘上放置8枚皇后,使得棋盘中每个横向、纵向、左上至右下斜向、右上至左下斜向均只有一枚皇后*/
5+
6+ const int N = 8 ; // 棋盘行数
7+ int a[N] = {0 }; // 表示棋盘,若a[2]=2,则表示在第3行第2列放一个皇后,因为同一行不能放两个皇后,所以只需要1维数组就可以表示一个棋盘。
8+
9+ int num = 0 ;// 解的个数
10+
11+ // 纵向,斜向,若没有有皇存在,则返回true;否则返回false;
12+ bool IsValid (int n)
13+ {
14+ for (int i = 0 ; i < n; i++)
15+ {
16+ if (a[i] == a[n] || (abs (a[i] - a[n]) == n - i))
17+ {
18+ return false ;
19+ }
20+ }
21+ return true ;
22+ }
23+
24+ // 打印出所有解
25+ void Print ()
26+ {
27+ printf (" 第%d种解:\n " ,++num);
28+ for (int i = 0 ; i < N; i++)
29+ {
30+ for (int j = 0 ; j < N; j++)
31+ {
32+ if (a[i] == j)
33+ {
34+ printf (" %d" , i);
35+ }
36+ else
37+ {
38+ printf (" #" );
39+ }
40+ }
41+ printf (" \n " );
42+ }
43+
44+ printf (" -----------------\n " );
45+ }
46+
47+ void Put (int n)
48+ {
49+ if (n == N)
50+ {
51+ Print ();
52+ return ;
53+ }
54+ for (int i = 0 ; i < N; i++)
55+ {
56+ a[n] = i;
57+ if (IsValid (n))
58+ {
59+ Put (n + 1 );
60+ }
61+ }
62+ }
63+
64+ int main ()
65+ {
66+ Put (0 );
67+ return 0 ;
68+ }
You can’t perform that action at this time.
0 commit comments