循环里面套循环,注意循环条件和终止条件即可:

//
// Created by jt on 2020/8/21.
//
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n, m;
    cin >> n >> m;
    vector<vector<int> > vec(n, vector<int>(m));
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) { cin >> vec[i][j]; }
    }
    vector<int> res;
    // top必须小于等于bottom,left必须小于等于right
    int top = 0, bottom = n - 1, left = 0, right = m - 1;
    while (true) {
        // 从上到下
        for (int i = top; i <= bottom; ++i) res.push_back(vec[i][left]);
        if (++left > right) break;
        // 从左到右
        for (int i = left; i <= right; ++i) res.push_back(vec[bottom][i]);
        if (--bottom < top) break;
        // 从下到上
        for (int i = bottom; i >= top; --i) res.push_back(vec[i][right]);
        if (--right < left) break;
        // 从右到左
        for (int i = right; i >= left; --i) res.push_back(vec[top][i]);
        if (++top > bottom) break;
    }
    for (int i = 0; i < n*m; ++i) {
        cout << res[i];
        if (i != n*m - 1) cout << ' ';
        else cout << endl;
    }
}