59. 螺旋矩阵 II

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

示例:

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

思路:这题目很简单,在54题的基础上稍微改一下就好了。

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> matrix(n, vector<int>(n,0));
        int l=0, r=n-1, up=0, low=n-1, a=1;
        while(l<=r && up<=low){
            for(int j=l; j<=r; ++j)
                matrix[up][j] = a++; 
            for(int i=up+1; i<=low; ++i)
                matrix[i][r] = a++;
            for(int j=r-1; low>up && j>=l; --j)
                matrix[low][j] = a++;
            for(int i=low-1; r>l && i>up; --i)
                matrix[i][l] = a++;
            ++l,  --r, ++up, --low;
        }
        return matrix;
    }
};

猜你喜欢

转载自blog.csdn.net/scarlett_guan/article/details/80250675