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> > ans;
        int i,j,x1,x2,k;
        
        for(i=0;i<n;i++)
        {
            vector<int> vec2;
            for(j=0;j<n;j++)
                vec2.push_back(0);
            ans.push_back(vec2);
        }
            
        k=1;
        x1=0;x2=n-1;
        while(k<=n*n)
        {
            for(i=x1;i<=x2;i++)
                ans[x1][i]=k++;
            
            for(i=x1+1;i<=x2;i++)
                  ans[i][x2]=k++;
                  
            if(x1!=x2)
               for(i=x2-1;i>=x1;i--)
                  ans[x2][i]=k++;
                  
            if(x1!=x2)
                for(i=x2-1;i>x1;i--)
                   ans[i][x1]=k++;
            x1++;x2--;
        }
        return ans;
    }
};