leetcode:Spiral Matrix II

来源:互联网 发布:php utf8转换为gbk 编辑:程序博客网 时间:2024/06/05 03:44

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 ]]

Show Tags
Have you met this question in a real interview? 
Yes
 
No

Discuss



class Solution {public:vector<vector<int> > generateMatrix(int n) {        vector<vector<int> >  retVtr(n, vector<int>(n));        if (n == 0)    {        return retVtr;    }        int offset = 0;    int N = n*n;    int curVal = 1;    while (curVal <= N)    {        if (curVal == N)        {            retVtr[offset][offset] = curVal;            break;        }                for (int idx=offset; idx<n-1-offset && curVal<=N; idx++)            retVtr[offset][idx] = curVal++;                for (int idx=offset; idx<n-1-offset && curVal<=N; idx++)            retVtr[idx][n-1-offset] = curVal++;                for (int idx=n-1-offset; idx>offset && curVal<=N; idx--)            retVtr[n-1-offset][idx] = curVal++;                for (int idx=n-1-offset; idx>offset && curVal<=N; idx--)            retVtr[idx][offset] = curVal++;                offset++;    }        return retVtr;}};





0 0
原创粉丝点击