Run ID 作者 问题 语言 测评结果 Time Memory 代码长度 提交时间
141303 胡海峰老师 方阵填数 C++ Time Limit Exceeded 1000 MS 308 KB 1863 2025-12-22 10:30:20

Tests(0/3):


Code:

#include <iostream> using namespace std; int main() { int N; cin >> N; // 创建N×N的矩阵,全部初始化为0 int matrix[101][101] = {0}; // 起始位置:第一行最后一列 (0, N-1) 注意:这里使用0-based索引 int row = 0; // 当前行 int col = N - 1; // 当前列 int currentNumber = 1; // 当前要填的数字 // 第一个方向:向下 int direction = 0; // 0:向下, 1:向左, 2:向上, 3:向右 // 初始步长 int stepSize = N - 1; // 填充第一个位置 matrix[row][col] = currentNumber; currentNumber++; // 开始螺旋填充 while (currentNumber <= N * N) { // 根据当前方向移动 for (int i = 0; i < stepSize; i++) { // 更新位置 switch (direction) { case 0: row++; break; // 向下 case 1: col--; break; // 向左 case 2: row--; break; // 向上 case 3: col++; break; // 向右 } // 填充数字 matrix[row][col] = currentNumber; currentNumber++; // 如果已经填满,退出 if (currentNumber > N * N) break; } // 改变方向 direction = (direction + 1) % 4; // 每完成两个方向,步长减1 if (direction % 2 == 0) { // 每当回到向下或向上方向时 stepSize--; } } // 输出结果 for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // 为了对齐,使用cout.width(3) cout.width(3); cout << matrix[i][j] << " "; } cout << endl; } return 0; }