59. Spiral Matrix II
problem description
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]algorithm thought
code
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n,vector<int>(n,0));
vector<int> nstep{n,n-1};
vector<vector<int>> move{{0,1},{1,0},{0,-1},{-1,0}};
int i=0,j=-1;
int pos=0;
int tmp=1;
while(nstep[pos%2]){
for(int k=0;k<nstep[pos%2];++k){
i+=move[pos%4][0];j+=move[pos%4][1];
//cout<<i<<'-'<<j<<' ';
res[i][j]=tmp++;
}
nstep[pos%2]--;
pos++;
}
return res;
}
};algorithm analysis
Last updated