题目:
描述在n*n方陈里填入1,2,...,n*n,要求填成蛇形。例如n=4时方陈为: 10 11 12 1 9 16 13 2 8 15 14 3 7 6 5 4 输入直接输入方陈的维数,即n的值。(n<=100)输出输出结果是蛇形方陈。 样例输入 3 样例输出 7 8 1 6 9 2 5 4 3
代码:
# include <stdio.h> # include <string.h> # define maxn 20 int a[maxn][maxn]; int main(void) { int n, x, y, top = 0; //这里把top初始化为0,以便后面的递加; scanf("%d", &n); //输入方针的行或列 memset(a, 0, sizeof(a)); //依附于string.h头文件的函数,作用是清空数组(即都为0) top = a[x = 0][y = n - 1] = 1;//从右上角开始 第一个坐标为a[0][n-1] while (top < n*n) //top 是个数,如果n是四根据题例可以得出 top一直加到16,程序结束 { while (x + 1 < n && !a[x + 1][y]) a[++x][y] = ++top;//向下走 while (y - 1 >= 0 && !a[x][y - 1]) a[x][--y] = ++top;//向左走 while (x - 1 >= 0 && !a[x - 1][y]) a[--x][y] = ++top;//向上走 while (y + 1 < n && !a[x][y + 1]) a[x][++y] = ++top; //向右走 }//上面的a数组依靠坐标的变换来实现移动;依靠top累加来实现输出1-16(if n == 4) 因为对a数组清零了所以!a[][]为1 即为真! for (x = 0; x < n; x++)//输出数组 { for (y = 0; y < n; y++) printf("=", a[x][y]); printf("\n"); } getchar(); getchar(); return 0; }