这个问题直接用4个while循环就可以写出来,注意一下边界处理就行了
1 #include <stdio.h> 2 #include <string.h> 3 int a[103][103]; 4 int main() 5 { 6 int n; 7 while(~scanf("%d", &n)) 8 { 9 memset(a, 0, sizeof(a)); 10 int num = 1; 11 int cnt = n * n; 12 int i = 0, j = n - 1; 13 a[0][n - 1] = 1; 14 while (num < cnt) 15 { 16 while (i + 1 < n && a[i + 1][j] == 0)//向下填数 17 a[++i][j] = ++num; 18 while (j - 1 >= 0 && a[i][j - 1] == 0)//向左填数 19 a[i][--j] = ++num; 20 while (i - 1 >= 0 && a[i - 1][j] == 0)//向上填数 21 a[--i][j] = ++num; 22 while (j + 1 < n && a[i][j + 1] == 0)//向右填数 23 a[i][++j] = ++num; 24 25 } 26 for (int i = 0; i < n; i++) 27 { 28 for (int j = 0; j < n; j++) 29 printf("%d ", a[i][j]); 30 puts(""); 31 } 32 } 33 return 0; 34 35 }