【C++刷题笔记】螺旋矩阵 - 上三角

#include "iostream"
#include "vector"
using namespace std;

vector<vector<int>> generateMatrix_T(int n) {
    vector<vector<int>> v(n, vector<int>(n, 0));
    int count = 1;
    int x = 0, y = 0;
    int startX = 0, startY = 0;
    int num = n * (n + 1) / 2;
    while (count <= num) {
        x = startX, y = startY;
        while (y < n) {
            v[x][y] = count;
            count++;
            y++;
        }
        y -= 2;
        x++;
        while (x < n) {
            v[x][y] = count;
            count++;
            x++;
            y--;
        }
        x -= 2;
        y++;
        while (x > startX) {
            v[x][y] = count;
            count++;
            x--;
        }
        n -= 2;
        startX = startX + 1;
        startY = startY + 1;
    }
    return v;
}

int main(){
    int n = 0;
    cin >> n;
    auto ret = generateMatrix_T(n);
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            cout << ret[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

【C++刷题笔记】螺旋矩阵 - 上三角_第1张图片

你可能感兴趣的:(刷题,C++,c++,笔记,矩阵)