59. Spiral Matrix II

来源:互联网 发布:淘宝网女士套装阔腿裤 编辑:程序博客网 时间:2024/05/01 22:25

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

思路:直接打印即可,注意直接赋值要初始化(push_back的不用),还有n为基数的时候要处理最后中间的那个点。

class Solution {public:    vector<vector<int>> generateMatrix(int n) {        vector<vector<int>> res(n, vector<int>(n,0)); //记得初始化        int left = 0, right = n-1, top = 0, bottom = n -1;        int k = 1;        while(left < right && top < bottom)        {            for(int j =left; j < right; j++)            {                res[top][j] = k++;            }            for(int j = top; j < bottom; j++)            {                res[j][right] = k++;            }            for(int j = right; j > left; j--)            {                res[bottom][j] = k++;            }            for(int j = bottom; j > top; j--)            {                res[j][left] = k++;            }            top++;            bottom--;            left++;            right--;        }        if(n%2 == 1)        {            res[n/2][n/2] = k;        }        return res;    }};
0 0
原创粉丝点击