提交时间:2026-06-17 20:00:18

运行 ID: 91862

#include <iostream> #include <vector> using namespace std; int main() { // 优化IO ios::sync_with_stdio(false); cin.tie(NULL); int m, n; if (!(cin >> m >> n)) return 0; vector<vector<int>> matrix(m, vector<int>(n)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { cin >> matrix[i][j]; } } if(n == 1 && m == 1) { cout << matrix[0][0] << endl ; return 0 ; } int top = 0, bottom = m - 1; int left = 0, right = n - 1; bool first = true; // 用于控制空格输出 while (top <= bottom && left <= right) { // 1. 向下:遍历左列 for (int i = top; i <= bottom; ++i) { if (!first) cout << " "; cout << matrix[i][left]; first = false; } left++; // 2. 向右:遍历底行 if (left <= right) { // 检查边界有效性 for (int j = left; j <= right; ++j) { cout << " " << matrix[bottom][j]; } bottom--; } // 3. 向上:遍历右列 if (top <= bottom) { // 检查边界有效性 for (int i = bottom; i >= top; --i) { cout << " " << matrix[i][right]; } right--; } // 4. 向左:遍历顶行 if (left <= right) { // 检查边界有效性 for (int j = right; j >= left; --j) { cout << " " << matrix[top][j]; } top++; } } cout << endl; return 0; }