Skip to content

Commit fd6f87d

Browse files
committed
八皇后问题递归实现
1 parent 25749c3 commit fd6f87d

File tree

1 file changed

+140
-0
lines changed

1 file changed

+140
-0
lines changed

EightQueens/main.c

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
/*
2+
在8*8国际象棋棋盘上,要求在每一行放置一个皇后,且能做到在竖方向,斜方向都没有冲突。
3+
4+
5+
递归算法:
6+
1.先有个结束条件
7+
2.未满足条件,则进入递归。
8+
*/
9+
10+
#include <stdio.h>
11+
#include <stdlib.h>
12+
13+
int count = 0;
14+
15+
//判断 行 列 斜线 方向是否危险
16+
int notDanger( int row, int j, int (*chess)[8] )
17+
{
18+
int i, k;
19+
int flag_1 = 0,flag_2 = 0,flag_3 = 0,flag_4 = 0,flag_5 = 0;
20+
21+
//判断列
22+
for( i=0; i<8; i++ )
23+
{
24+
if( *(*(chess+i)+j) != 0 )
25+
{
26+
flag_1 = 1;
27+
break;
28+
}
29+
}
30+
31+
//判断左上
32+
for( i=row,k=j; i>=0 && k>=0; i--,k-- )
33+
{
34+
if( *(*(chess+i)+k) != 0 )
35+
{
36+
flag_2 = 1;
37+
break;
38+
}
39+
}
40+
41+
//判断右下
42+
for( i=row,k=j; i<8 && k<8; i++,k++ )
43+
{
44+
if( *(*(chess+i)+k) != 0 )
45+
{
46+
flag_3 = 1;
47+
break;
48+
}
49+
}
50+
51+
//判断左下
52+
for( i=row,k=j; i<8 && k>=0; i++,k-- )
53+
{
54+
if( *(*(chess+i)+k) != 0 )
55+
{
56+
flag_4 = 1;
57+
break;
58+
}
59+
}
60+
61+
//判断右上
62+
for( i=row,k=j; i>=0 && k<8; i--,k++ )
63+
{
64+
if( *(*(chess+i)+k) != 0 )
65+
{
66+
flag_5 = 1;
67+
break;
68+
}
69+
}
70+
71+
if( flag_1 || flag_2 || flag_3 || flag_4 || flag_5 )
72+
return 0;
73+
else
74+
return 1;
75+
76+
}
77+
78+
//参数 row 起始行
79+
//参数 col 列
80+
//参数 (*chess)[8] 行指针
81+
void eightQueens( int row, int col, int (*chess)[8] )
82+
{
83+
int chess_2[8][8], i, j;
84+
85+
for( i=0; i<8; i++ )
86+
{
87+
for( j=0; j<8; j++ )
88+
{
89+
chess_2[i][j] = chess[i][j];
90+
}
91+
}
92+
93+
if( 8 == row )
94+
{
95+
printf("NO.%d:\n", ++count);
96+
for( i=0; i<8; i++ )
97+
{
98+
for( j=0; j<8; j++ )
99+
{
100+
printf("%d ", chess[i][j]);
101+
}
102+
printf("\n");
103+
}
104+
printf("\n");
105+
}
106+
else
107+
{
108+
for( j=0; j<col; j++ )
109+
{
110+
if( notDanger( row, j, chess_2 ) )
111+
{
112+
for( i=0; i<8; i++ )
113+
{
114+
*(*(chess_2+row)+i) = 0;
115+
}
116+
117+
*(*(chess_2+row)+j) = 1;
118+
119+
eightQueens( row+1, col, chess_2 );
120+
}
121+
}
122+
}
123+
}
124+
125+
int main()
126+
{
127+
int chess[8][8], i, j;
128+
129+
for( i=0; i<8; i++ )
130+
{
131+
for( j=0; j<8; j++ )
132+
{
133+
chess[i][j] = 0;
134+
}
135+
}
136+
137+
eightQueens( 0, 8, chess );
138+
139+
return 0;
140+
}

0 commit comments

Comments
 (0)