一遍AC #include <stdio.h> /* 描述 在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 */ int main(){ int n; while(~scanf("%d", &n)){ int a[n][n]; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) a[i][j] = 0; int x, y, number;//循环变量+计数的number //预处理,填外圈 a[0][n-1] = 1; for(y = 0, number = 1; y < n; y++) a[y][n-1] = number++; for(x = n-2; x >= 0; x--) a[n-1][x] = number++; for(y = n-2; y >= 0; y--) a[y][0] = number++; for(x = 1; x <= n-2; x++) a[0][x] = number++; x = 0, y = n-2; while(number <= n*n){ //south 从a[0][n-2]开始 //printf("%d~~~\n", a[x][y]); while((number <= (n*n)) && !a[x+1][y]) a[++x][y] = number++; //west while((number <= n*n) && !a[x][y-1]) a[x][--y] = number++; //north while((number <= n*n) && !a[x-1][y]) a[--x][y] = number++; //east while((number <= n*n) && !a[x][y+1]) a[x][++y] = number++; } //输出 for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(j==0) printf("%d", a[i][j]); else printf(" %d", a[i][j]); } puts(""); } } return 0; }
时间: 2024-10-15 00:28:26