# Is this the best solution?

• My thought is like this:

1. cut the spiral into squares, fill the number clockwisely in the 4 edges of each square;
2. start from point (i,i), filling the outer layer cycle, which, for example, is filling in 1,2,3,4 then 5,6,7, then 8, 9, 10, then11, 12;
3. jump to (i+1, i+1), and do the same thing, filling 13,14 then 15 then 16;
4. stop when i reaches n/2;
5. fill in the last number in A[n/2][n/2] if n is odd;
``````vector<vector<int> > generateMatrix(int n) {
vector <vector<int>> ans;
if (n < 1) return ans;
ans.resize(n);
for (int i = 0; i < n; i++)
ans[i].resize(n);
int val = 1;
for (int i = 0; i < n / 2; i++){
for (int j = i; j < n - i; j++) ans[i][j] = val++;
for (int j = i + 1; j < n - i; j++) ans[j][n - i - 1] = val++;
for (int j = n - i - 2; j> i - 1; j--) ans[n - i - 1][j] = val++;
for (int j = n - i - 2; j>i; j--) ans[j][i] = val++;
}
if (n % 2 != 0) ans[n / 2][n / 2] = val;
return ans;
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.