输入一个n, 在n*n的方阵里填成蛇形,如:
输入:5
输出:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | #include<stdio.h> #define RIGHT 0 #define DOWN 1 #define LEFT 2 #define UP 3 static int grid[1000][1000]; //静态变量初值为0 int main(void) { int n; scanf("%d", &n); int i = 0, j = 0, direction = RIGHT; for(int k = 1; k <= n * n; k++) { grid[i][j] = k; switch(direction % 4) { //如果前方有数字或者到达边界就变换方向 case RIGHT: if(j + 1 >= n || grid[i][j + 1]) { direction++; } break; case DOWN: if(i + 1 >= n || grid[i + 1][j]) { direction++; } break; case LEFT: if(j - 1 < 0 || grid[i][j - 1]) { direction++; } break; case UP: if(i - 1 < 0 || grid[i - 1][j]) { direction++; } break; } switch(direction % 4) { //向当前方向移动一格 case RIGHT: j++; break; case DOWN: i++; break; case LEFT: j--; break; case UP: i--; break; } } for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { printf("%d ", grid[i][j]); //输出 } puts(""); //换行 } return 0; } |
发表回复