Spiral Matrix II

来源:互联网 发布:成都海光集成电路 知乎 编辑:程序博客网 时间:2024/06/17 22:13

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

For example,
Given n = 3,

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


Solution:

class Solution {public:    vector<vector<int>> generateMatrix(int n) {        vector<vector<int> > res;        if(n <= 0) return res;        res.resize(n);        for(int i = 0; i < n; ++i) res[i].resize(n);        int lu = 0, rd = n - 1, k = 0;        while(lu <= rd)        {            for(int i = lu; i <= rd; ++i) res[lu][i] = ++k;            for(int i = lu + 1; i <= rd; ++i) res[i][rd] = ++k;            for(int i = rd - 1; i >= lu; --i) res[rd][i] = ++k;            for(int i = rd - 1; i > lu; --i) res[i][lu] = ++k;            lu++;            rd--;        }                return res;    }};


0 0
原创粉丝点击