首先我们先看一下蛇形数组是什么
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
我们可以看到,它每一圈的数字都是依次加1的,那么就很容易想到用圈来实现,先算除要求的数组有多少圈,分别做4个while循环来进行。
AC实现代码如下
#include<stdio.h>
#include<string.h>
#define max 100
int a[max][max];
int main(void)
{
int n, x, y, tot = 0; while (scanf("%d", &n) != EOF) {
memset(a, 0, sizeof(a));
tot = a[x = 0][y = n - 1] = 1;
while (tot < n*n) {
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;
while (y + 1 < n && a[x][y + 1]==0) a[x][++y] = ++tot;
}
for (x = 0; x < n; x++)
{
for (y = 0; y < n; y++) printf("%d ", a[x][y]);
printf("\n");
}
}
return 0;
}