```
vector<vector<int>> generateMatrix(int n)
{
vector<vector<int>> M(n, vector<int>(n, n * n));
// changes in direction: right, down, left, up
const int drow[] = {0, 1, 0, -1};
const int dcol[] = {1, 0, -1, 0};
auto x = 1;
// make n/2 spirals, each smaller
for(int k = 0; 0 <= n; n -= 2, k++)
{
int row = k;
int col = k;
for(int i : {0, 1, 2, 3})
{
for (int j = 0; j < n - 1; ++j)
{
M[row][col] = x++;
row += drow[i];
col += dcol[i];
}
}
}
return M;
}
```