Spiral Matrix II
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 ] ]
Tips:
This problem is easier than Spiral Matrix because we can check whether the position is filled.
Solution:class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > result;
result.resize(n);
for(int i=0;i<n;++i){
result[i].resize(n);
}
int dir[][2]={{0,1},{1,0},{0,-1},{-1,0}};
int index=0,x=0,y=0;
for(int i=1;i<=n*n;++i){
result[x][y]=i;
int nx=x+dir[index][0];
int ny=y+dir[index][1];
if(nx>n-1||nx<0||ny>n-1||ny<0||result[nx][ny]!=0){
++index;
index%=4;
nx=x+dir[index][0];
ny=y+dir[index][1];
}
x=nx;
y=ny;
}
return result;
}
};