蛇形填数很好的思想就是循环判断与填数,循环判断条件是很好的思路,思想可以移植到其他程序中。
1 /*
2 蛇形填数
3 */
4
5 #include <stdio.h>
6 #include <string.h>
7
8
9 int num[10][10];
10
11 int main()
12 {
13 int x=0;
14 int y=0;
15 int t=0;
16
17 const int n=10;
18
19 memset(num,0,sizeof(num));
20
21 t=1;
22
23 num[x=0][y=9]=1;
24
25 while(t<10*10)
26 {
27 while(x+1<n&&num[x+1][y]==0)
28 {
29 num[++x][y]=++t;
30 }
31 while(y-1>=0&&num[x][y-1]==0)
32 {
33 num[x][--y]=++t;
34 }
35 while(x-1>=0&&num[x-1][y]==0)
36 {
37 num[--x][y]=++t;
38 }
39 while(y+1<n&&num[x][y+1]==0)
40 {
41 num[x][++y]=++t;
42 }
43 }
44
45 for(x=0;x<10;x++)
46 {
47 for(y=0;y<10;y++)
48 {
49 printf("%d ",num[x][y]);
50 }
51 printf("
");
52 }
53
54 return 0;
55 }