9 {
10 vector<vector<int>> matrix(n, vector<int>(n));
11
12 int left = 0, right = n - 1, top = 0, bottom = n - 1;
13 int num = 1;
14 while (left <= right && top <= bottom)
15 {
16 for (int j = left; j <= right; ++j)
17 matrix[top][j] = num++;
18 ++top;
19
20 for (int i = top; i <= bottom; ++i)
21 matrix[i][right] = num++;
22 --right;
23
24 if (top <= bottom)
25 {
26 for (int j = right; j >= left; --j)
27 matrix[bottom][j] = num++;
28 --bottom;
29 }
30
31 if (left <= right)
32 {
33 for (int i = bottom; i >= top; --i)
34 matrix[i][left] = num++;
35 ++left;
36 }
37 }
38 return matrix;
39 }