3.2_蛇形填数

 1 #include<stdio.h>
 2 #include<string.h>
 3 
 4 #define maxn 20
 5 
 6 int a[maxn][maxn];
 7 
 8 int main()
 9 {
10     memset(a, 0, sizeof(a));
11 
12     int x = 0;
13     int y = maxn - 1;
14     int tot = a[x][y]=1;
15 
16 /*
17 
18     以下循环有逻辑问题,我们应当是讨论下一个位置合不合理而不是当前位置
19     这个循环很容易造成死循环.即使把14行改为int tot=1;也只能执行其中的
20     第一个循环第二个及以后的循环会因为a[x][y]!=0而无法执行
21 
22     while (tot <= maxn*maxn)
23     {
24         while (x<maxn && !a[x][y])
25             a[x++][y] = tot++;
26         while (y >= 0 && !a[x][y])
27             a[x][y--] = tot++;
28         while (x >= 0 && !a[x][y])
29             a[x--][y] = tot++;
30         while (y<maxn && !a[x][y])
31             a[x][y++] = tot++;
32     }
33 */
34     while (tot < maxn*maxn)
35     {
36         while (x+1<maxn && !a[x+1][y])
37             a[++x][y] = ++tot;
38         while (y-1 >= 0 && !a[x][y-1])
39             a[x][--y] = ++tot;
40         while (x-1 >= 0 && !a[x-1][y])
41             a[--x][y] = ++tot;
42         while (y+1<maxn && !a[x][y+1])
43             a[x][++y] = ++tot;
44     }
45 
46     for (int i = 0;i<maxn;i++)
47     {
48         for (int j = 0;j<maxn;j++)
49         {
50             if (j == maxn - 1)
51                 printf("%3d
", a[i][j]);
52             else
53                 printf("%3d ", a[i][j]);
54         }
55     }
56 
57     return 0;
58 }
Yosoro
原文地址:https://www.cnblogs.com/tclan126/p/7151522.html