Run ID:130010

提交时间:2025-09-07 11:40:42

#include <iostream> #include <vector> #include <iomanip> // 用于设置输出宽度 using namespace std; int main() { int n; cin >> n; // 初始化n×n的矩阵 vector<vector<int>> matrix(n, vector<int>(n, 0)); // 定义四个方向的偏移量:右、下、左、上 int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; int dir_index = 0; // 初始方向向右 // 初始位置 int row = 0, col = 0; // 填充矩阵 for (int num = 1; num <= n * n; ++num) { matrix[row][col] = num; // 计算下一个位置 int next_row = row + directions[dir_index][0]; int next_col = col + directions[dir_index][1]; // 检查下一个位置是否合法(在范围内且未被填充) if (next_row >= 0 && next_row < n && next_col >= 0 && next_col < n && matrix[next_row][next_col] == 0) { row = next_row; col = next_col; } else { // 改变方向 dir_index = (dir_index + 1) % 4; row += directions[dir_index][0]; col += directions[dir_index][1]; } } // 打印矩阵,每个数字占4个域宽 for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { cout << setw(4) << matrix[i][j]; } cout << endl; } return 0; }