#include <stdio.h> int main() { int arr[20][20], n;//定义 scanf("%d", &n); int up = 0, left = 0, right = n - 1, down = n - 1;//从四个方向考虑问题 int x = 1;//记录数据元素的大小 while (x <= n * n)//循环条件 { for (int i = left; i <= right; i++)//第一方向,从左向右 { arr[up][i] = x++; } up++;//往下走 for (int i = up; i <= down; i++) //right列不动,上下动 { arr[i][right] = x++; } right--;//往左走 for(int i = right;i>=left;i--)//down不动,列数元素动 { arr[down][i] = x++; } down--;//向上走 for(int i = down;i>=up;i--)//left不动,上下动 { arr[i][left] = x++; } left++; } for(int i = 0;i < n;i++)//打印输出 { for(int j = 0;j<n;j++) { printf("%d ",arr[i][j]); } printf("\n"); } return 0; }