Given an integer n, generate a square matrix filled with elements from 1 to n 2 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> > v(n, vector<int>(n));
int i = 0, j = 0;
int cnt = 1;
int m = n * n;
int raw = 0, col = 0;
int raw1 = n-1, col1 = n-1;
if(n & 1)
{
v[n/2][n/2] = m;
m -= 1;
}
while(cnt <= m)
{
while(j < col1)
{
v[i][j++] = cnt++;
}
while(i < raw1)
{
v[i++][j] = cnt++;
}
while(j > col)
{
v[i][j--] = cnt++;
}
while(i > raw)
{
v[i--][j] = cnt++;
}
++i;
++j;
++col;
++raw;
--col1;
--raw1;
}
return v;
}
};