Run ID 作者 问题 语言 测评结果 Time Memory 代码长度 提交时间
78466 彭士宝 数字方阵 C++ Wrong Answer 1 MS 272 KB 1511 2024-06-22 09:45:32

Tests(0/2):


Code:

#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; }


Run Info:

------Input------
5
------Answer-----
1 1 1 1 1 1 2 2 2 1 1 2 3 2 1 1 2 2 2 1 1 1 1 1 1
------Your output-----
Enter the value of n (2<=n<=9): 1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9