Run ID:158511

提交时间:2026-08-22 13:49:39

#include <iostream> #include <iomanip> using namespace std; int main() { int n; cin >> n; int a[105][105] = {0}; int num = 1; // 边界 int top = 0; int bottom = n - 1; int left = 0; int right = n - 1; while(num <= n * n) { // 1. 最右边一列:从上往下 for(int i = top; i <= bottom && num <= n*n; i++) { a[i][right] = num++; } right--; // 2. 最下边一行:从右往左 for(int j = right; j >= left && num <= n*n; j--) { a[bottom][j] = num++; } bottom--; // 3. 最左边一列:从下往上 for(int i = bottom; i >= top && num <= n*n; i--) { a[i][left] = num++; } left++; // 4. 最上边一行:从左往右 for(int j = left; j <= right && num <= n*n; j++) { a[top][j] = num++; } top++; } // 输出方阵 for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(j > 0) cout << " "; cout << a[i][j]; } cout << endl; } return 0; }