Problem
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) {
int begin = 0, end = n - 1;
vector<vector<int> > ret (n, vector<int>(n, 0));
int num = 1;
while(begin < end) {
for(int i = begin; i < end; ++i) ret[begin][i] = num++;
for(int i = begin; i < end; ++i) ret[i][end] = num++;
for(int i = end; i > begin; --i) ret[end][i] = num++;
for(int i = end; i > begin; --i) ret[i][begin] = num++;
++begin;
--end;
}
if(begin == end) {
ret[begin][begin] = num;
}
return ret;
}
};