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> > vec(n,vector<int>(n,0));
int i=0,j=0;
int currentValue = 1;
while(currentValue <= n*n)
{
for(;j<n;j++)
{
if(vec[i][j]!=0)
break;
else
vec[i][j]= currentValue++;
}
j--;
i++;
for(;i<n;i++)
{
if(vec[i][j]!=0)
break;
else
vec[i][j]= currentValue++;
}
i--;
j--;
for(;j>=0;j--)
{
if(vec[i][j]!=0)
break;
else
vec[i][j]= currentValue++;
}
j++;
i--;
for(;i>=0;i--)
{
if(vec[i][j]!=0)
break;
else
vec[i][j]= currentValue++;
}
i++;
j++;
}
return vec;
}
};