首页 > 代码库 > 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 ] ]
class Solution {
public:
    vector<vector<int> > generateMatrix(int n) 
    {
       vector<vector<int>>  result;
       if(n==0return result;
       
       for(int i=0;i<n;i++)
       {
           vector<int> v;
           for(int j=0;j<n;j++)
            v.push_back(0);
            result.push_back(v);
        }
        int len=n-1;
        int num=1;
        int x=0;
        result[0][0]=1;
        while(len>=1)
        {
            for(int i=0;i<len;i++)
                result[x][x+i]=num++;
            for(int i=0;i<len;i++)
                result[x+i][x+len]=num++;
            for(int i=0;i<len;i++)
                result[x+len][x+len-i]=num++;
            for(int i=0;i<len;i++)
                result[x+len-i][x]=num++;
            len=len-2;
            x++;
        }
        if(len==0) result[x][x]=num;
        return result;
    }
};