In case anyone is interested in a simple direction based solution...

```
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > res(n, vector<int>(n, 0));
if( n == 1 )
res[0][0] = 1;
if(n <= 1)
return res;
int dx[] = {0, 1, 0,-1}, dy[] = {1, 0,-1, 0};
int d = 0, i = 0, j = 0, v = 1;
while(true){
res[i][j] = v++;
if( i + dx[d] == n || j + dy[d] == n || res[ i + dx[d] ][ j + dy[d] ])
d = (d+1)%4;
i += dx[d], j += dy[d];
if(res[i][j])
break;
}
return res;
}
};
```