Run ID 作者 问题 语言 测评结果 Time Memory 代码长度 提交时间
136261 彭士宝 蛇形矩阵 C++ Wrong Answer 1 MS 276 KB 1348 2025-11-09 23:00:25

Tests(0/10):


Code:

#include <iostream> #include <vector> #include <iomanip> // 用于控制输出格式 using namespace std; void printMatrix(const vector<vector<int>>& matrix) { for (const auto& row : matrix) { for (int val : row) { cout << setw(3) << val; // 每个数字占3个字符宽度 } cout << endl; } } int main() { int n; cin >> n; vector<vector<int>> matrix(n, vector<int>(n, 0)); int num = 1; // 当前填充的数字 int top = 0, bottom = n - 1, left = 0, right = n - 1; // 定义矩阵的边界 while (num <= n * n) { // 从左到右填充顶部行 for (int i = left; i <= right && num <= n * n; ++i) { matrix[top][i] = num++; } top++; // 从上到下填充右侧列 for (int i = top; i <= bottom && num <= n * n; ++i) { matrix[i][right] = num++; } right--; // 从右到左填充底部行 for (int i = right; i >= left && num <= n * n; --i) { matrix[bottom][i] = num++; } bottom--; // 从下到上填充左侧列 for (int i = bottom; i >= top && num <= n * n; --i) { matrix[i][left] = num++; } left++; } printMatrix(matrix); return 0; }


Run Info:

------Input------
4
------Answer-----
1 8 9 16 2 7 10 15 3 6 11 14 4 5 12 13
------Your output-----
1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7