Sunday, August 2, 2015

059 - Spiral Matrix II

Spiral Matrix II

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

Hide Tags
Array
Hide Similar Problems
(M) Spiral Matrix

还没做Spiral Matrix,不过以前CC做过类似的东西,每个边放n-1,四边放完然后往内收即可。
注意两个事儿:
1. 结果矩阵要直接把空间申请出来,不然就是segment fault了。
2. 如果n是奇数,最后中心的地方就还没填,需要补上(因为while没处理 len==0)。

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>>rst(n,vector<int>(n));
        int num=1, len=n-1, circle=0, tgt=n*n;
       
        while((len>=1)&&(num<=tgt))
        {
            //top
            for(int ii=0; ii<len; ++ii)
                rst[circle][circle+ii]=num++;


            //right
            for(int ii=0; ii<len; ++ii)
                rst[circle+ii][circle+len]=num++;


            //bottom
            for(int ii=0; ii<len; ++ii)
                rst[circle+len][circle+len-ii]=num++;


            //left
            for(int ii=0; ii<len; ++ii)
                rst[circle+len-ii][circle]=num++;


            len -= 2;
            circle++;

        }
       
        if(!len)
            rst[circle][circle]=tgt;

       
        return rst;
    }
};

4 ms.

No comments:

Post a Comment