给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

 

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        if (n == 0)
            return {};

        vector<vector<int>> mat;
        for (int i = 0; i < n; ++i)
            mat.push_back(vector<int>(n, 0));
        
        int i = 0, j = 0, val = 1;
        while (true)
        {
            while (j < n && mat[i][j] == 0)
                mat[i][j++] = val++;
            if (val > n * n)
                break;
            i++;
            j--;
            while (i < n && mat[i][j] == 0)
                mat[i++][j] = val++;
            j--;
            i--;
            while (j >= 0 && mat[i][j] == 0)
                mat[i][j--] = val++;
            if (val > n * n)
                break;
            i--;
            j++;
            while (i >= 0 && mat[i][j] == 0)
                mat[i--][j] = val++;
            j++;
            i++;
        }
        
        return mat;
    }
};