Problem Description在n*n方阵里填入1,2,…,n*n,要求填成蛇形,例如n=4时方阵为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4Input对于每个测试实例,输出结果是蛇形方阵 n<=20Output对于每个测试实例,输出结果是蛇形方程。注意:每行最后一个数字后面没有空格。
include
include
define MAXN 10
int a[MAXN][MAXN];
int main(int argc, const char * argv[]) {
int x,y,n,start = 0;
memset(a, 0, sizeof(a));
printf("请输入一个数:");
scanf("%d",&n);
start = a[x=0][y=n-1] = 1;
//代码的精髓
while (start < n*n) {
while (x+1<n && !a[x+1][y]) a[++x][y] = ++start; //下
while (y-1>=0 && !a[x][y-1]) a[x][--y] = ++start; //左
while (x-1>=0 && !a[x-1][y]) a[--x][y] = ++start; //上
while (y+1<n && !a[x][y+1]) a[x][++y] = ++start; //右
}
for (x = 0; x < n; x++) {
for (y = 0; y < n; y++) {
printf("%3d",a[x][y]);
}
printf("\n");
}
return 0;
}