Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
Have you met this question in a real interview?
Yes
No
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > retVtr(n, vector<int>(n));
if (n == 0)
{
return retVtr;
}
int offset = 0;
int N = n*n;
int curVal = 1;
while (curVal <= N)
{
if (curVal == N)
{
retVtr[offset][offset] = curVal;
break;
}
for (int idx=offset; idx<n-1-offset && curVal<=N; idx++)
retVtr[offset][idx] = curVal++;
for (int idx=offset; idx<n-1-offset && curVal<=N; idx++)
retVtr[idx][n-1-offset] = curVal++;
for (int idx=n-1-offset; idx>offset && curVal<=N; idx--)
retVtr[n-1-offset][idx] = curVal++;
for (int idx=n-1-offset; idx>offset && curVal<=N; idx--)
retVtr[idx][offset] = curVal++;
offset++;
}
return retVtr;
}
};