Run ID 作者 问题 语言 测评结果 Time Memory 代码长度 提交时间
141304 胡海峰老师 方阵填数 C++ Output Limit Exceeded 2 MS 312 KB 2753 2025-12-22 10:31:07

Tests(0/3):


Code:

#include <iostream> using namespace std; int main() { int N; cin >> N; // Step 1: 创建并初始化矩阵 int grid[101][101] = {0}; // Step 2: 定义初始位置和数字 int currentRow = 0; // 当前在第1行(0-based) int currentCol = N - 1; // 当前在最后1列 int num = 1; // 要填写的数字 // Step 3: 设置初始方向和步长 int dir = 0; // 方向: 0=下, 1=左, 2=上, 3=右 int steps = N - 1; // 初始步长 // Step 4: 填第一个数字 grid[currentRow][currentCol] = num; num++; cout << "=== 开始填充 ===" << endl; cout << "起始位置: (" << currentRow+1 << "," << currentCol+1 << ") 填数字: 1" << endl; // Step 5: 开始螺旋填充 while (num <= N * N) { // 原子操作1:按当前方向移动一步 for (int i = 0; i < steps; i++) { cout << "--- 移动一步 ---" << endl; // 原子操作2:更新位置 if (dir == 0) { // 向下 currentRow++; cout << "方向: 向下, 新位置: (" << currentRow+1 << "," << currentCol+1 << ")"; } else if (dir == 1) { // 向左 currentCol--; cout << "方向: 向左, 新位置: (" << currentRow+1 << "," << currentCol+1 << ")"; } else if (dir == 2) { // 向上 currentRow--; cout << "方向: 向上, 新位置: (" << currentRow+1 << "," << currentCol+1 << ")"; } else if (dir == 3) { // 向右 currentCol++; cout << "方向: 向右, 新位置: (" << currentRow+1 << "," << currentCol+1 << ")"; } // 原子操作3:填写数字 grid[currentRow][currentCol] = num; cout << ", 填数字: " << num << endl; num++; // 检查是否完成 if (num > N * N) break; } // 原子操作4:改变方向 cout << "=== 改变方向 ===" << endl; dir = (dir + 1) % 4; // 循环方向 // 原子操作5:调整步长(每两个方向后步长减1) if (dir % 2 == 0) { steps--; cout << "步长减少为: " << steps << endl; } } // Step 6: 输出结果 cout << "\n=== 最终矩阵 ===" << endl; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout.width(3); cout << grid[i][j] << " "; } cout << endl; } return 0; }