LetCode 59. 螺旋矩阵 II

static int x=[](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n, vector<int>(n));
        // 这里分别用4个变量记录矩阵的4个顶点
        int Left = 0, Right = n - 1, Top = 0, Bottom = n - 1;
        int count = 1;
        while(count <= n * n){
            for (int i = Left; i <= Right && count <= n * n; i++)
                res[Top][i] = count++;
            for (int i = Top + 1; i <= Bottom && count <= n * n; i++)
                res[i][Right] = count++;
            for (int i = Right - 1; i >= Left && count <= n * n; i--)
                res[Bottom][i] = count++;
            for (int i = Bottom - 1; i > Top && count <= n * n; i--)
                res[i][Left] = count++;
            Left++;
            Right--;
            Top++;
            Bottom--;
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/wbb1997/article/details/81003112