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 ] ]
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int tot=1,x=0,y=0;
vector<vector<int>> v(n,vector<int>(n));
if(n==1){
v[0][0]=1;
return v;
}
while(tot<n*n){
v[0][0]=1;
while(y+1<n&&!v[x][y+1]){
v[x][++y]=++tot;
}
while(x+1<n&&!v[x+1][y]){
v[++x][y]=++tot;
}
while(y-1>=0&&!v[x][y-1]){
v[x][--y]=++tot;
}
while(x-1>=0&&!v[x-1][y]){
v[--x][y]=++tot;
}
}
return v;
}
};