Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
C++
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n,vector<int>(n,0));
int left = 0;
int right = n - 1;
int top = 0;
int bottom = n - 1;
int num = 1;
while(true)
{
for(int i = left;i <= right;++i)
{
res[top][i] = num;
++num;
}
++top;
if(top > bottom)
break;
for(int i = top;i <= bottom;++i)
{
res[i][right] = num;
num++;
}
--right;
if(left > right)
break;
for(int i = right;i >= left;--i)
{
res[bottom][i] = num;
num++;
}
--bottom;
if(top > bottom)
break;
for(int i = bottom;i >= top;--i)
{
res[i][left] = num;
++num;
}
++left;
if(left > right)
break;
}
return res;
}