题目描述:给定一个m×n的数组将1-m*n的数填入数组中
如给定3x3数组,输出
1 2 3
8 9 4
7 6 5
思路:首先问题可以考虑为由外向内一环一环的构造。而构造每一个环时,可分为4个步骤,左→右,上→下,右→左,下→上。
分别定义最左列为left,最右列为right,最上行为up,最下行为down。初始时left = 0; right = n - 1, up = 0; down = m - 1;当前的行列为i,j; 当填入最后一个数时程序返回。
1 #include <stdio.h> 2 #define M 1024 3 #define N 1024 4 5 int main(){ 6 int m, n; 7 int a[M][N]; 8 while(scanf("%d%d", &m, &n) != EOF){ 9 int up = 0, down = m - 1; 10 int left = 0, right = n - 1; 11 int i = up, j = left; 12 int num = 1; 13 int flag = m * n + 1; 14 while(1){ 15 while(j <= right){ 16 a[i][j] = num++; 17 j++; 18 } 19 if(num == flag) break; 20 j--; 21 up++; 22 i = up; 23 while(i <= down){ 24 a[i][j] = num++; 25 i++; 26 } 27 if(num == flag) break; 28 i--; 29 right--; 30 j = right; 31 while(j >= left){ 32 a[i][j] = num++; 33 j--; 34 } 35 if(num == flag) break; 36 j++; 37 down--; 38 i = down; 39 while(i >= up){ 40 a[i][j] = num++; 41 i--; 42 } 43 if(num == flag) break; 44 i++; 45 left++; 46 j = left; 47 } 48 printf("output\n"); 49 for(i = 0; i < m; i++){ 50 for(j = 0; j < n; j++){ 51 printf("%d\t", a[i][j]); 52 } 53 printf("\n"); 54 } 55 } 56 return 0; 57 }
时间: 2024-10-12 17:41:42