Run ID:78465

提交时间:2024-06-22 09:45:21

#include <iostream> #include <vector> const int MAX_N = 9; // 最大n值 void print_spiral_matrix(int n) { int matrix[MAX_N][MAX_N] = {0}; // 初始化矩阵为0 int dx[4] = {0, 1, 0, -1}; // 右、下、左、上的x方向变化量 int dy[4] = {1, 0, -1, 0}; // 右、下、左、上的y方向变化量 int direction = 0; // 当前方向索引 int x = 0; // 当前x坐标 int y = 0; // 当前y坐标 int num = 1; // 当前数字 for (int i = 0; i < n * n; ++i) { matrix[x][y] = num++; // 填充当前位置 int next_x = x + dx[direction], next_y = y + dy[direction]; // 计算下一个位置 // 检查下一个位置是否越界或是否已填充 if (next_x < 0 || next_x >= n || next_y < 0 || next_y >= n || matrix[next_x][next_y] != 0) { direction = (direction + 1) % 4; // 改变方向 next_x = x + dx[direction]; next_y = y + dy[direction]; } x = next_x; y = next_y; } // 打印矩阵 for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { std::cout << matrix[i][j] << " "; } std::cout << std::endl; } } int main() { int n; std::cout << "Enter the value of n (2<=n<=9): "; std::cin >> n; if (n < 2 || n > MAX_N) { std::cout << "n is out of the acceptable range." << std::endl; return 1; } print_spiral_matrix(n); return 0; }