Loop right "++j", down "++i", left "j", up "i".
Only turn under two situations:

next step is outside of the matrix

next step has been filled
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n,0));
if(n==0) return res;
int k=1, total = n*n, i=0, j=0;
res[0][0] = 1;
while(k<total)
{
while(j+1<n && res[i][j+1]==0) res[i][++j] = ++k;
while(i+1<n && res[i+1][j]==0) res[++i][j] = ++k;
while(j1>=0 && res[i][j1]==0) res[i][j] = ++k;
while(i1>=0 && res[i1][j]==0) res[i][j] = ++k;
}
return res;
}