Snake Number

来源:互联网 发布:一辈子买不起房子知乎 编辑:程序博客网 时间:2024/04/26 11:19

蛇形数类似这样的数组

8
   1   2   3   4    5   6   7   8
28 29 30 31 32 33 34   9
27 48 49 50 51 52 35 10
26 47 60 61 62 53 36 11
25 46 59 64 63 54 37 12
24 45 58 57 56 55 38 13
23 44 43 42 41 40 39 14
22 21 20 19 18 17 16 15

类似的顺时针,逆时针都可以修改一下代码顺序

    while (y+1 < n && a[x][y+1] == 0) a[x][++y] = ++tot;    while (x+1 < n && a[x+1][y] == 0) a[++x][y] = ++tot;    while (y-1 >= 0 && a[x][y-1] == 0) a[x][--y] = ++tot;    while (x-1 >= 0 && a[x-1][y] == 0) a[--x][y] = ++tot;
以上是顺时针方式。

#include <stdio.h>#define MAXN 20int a[MAXN][MAXN];int main(void){  int n;  int x = 0, y = 0, tot = 1;  scanf("%d", &n);  a[0][0] = 1;  while(tot < n * n) {    while (y+1 < n && a[x][y+1] == 0) a[x][++y] = ++tot;    while (x+1 < n && a[x+1][y] == 0) a[++x][y] = ++tot;    while (y-1 >= 0 && a[x][y-1] == 0) a[x][--y] = ++tot;    while (x-1 >= 0 && a[x-1][y] == 0) a[--x][y] = ++tot;  }  for (x = 0; x < n; x++) {    for (y = 0; y < n; y++)      printf("%3d ", a[x][y]);    printf("\n");  }  return 0;}

以上代码可以解决类似从四个顶点开始的蛇形数组。


0 0