```
public class Solution {
public int[][] generateMatrix(int n) {
int k = 1;
int[][] m = new int[n][n];
// l: layer, w: edge width of that layer
for (int l = 0, w = n - 1; l < n / 2; l++, k += 4 * w, w -= 2) {
for (int i = l; i < l + w; i++) { // i: ith item on that edge
m[l][i] = k + i - l + w * 0;
m[i][n-1-l] = k + i - l + w * 1;
m[n-1-l][n-1-i] = k + i - l + w * 2;
m[n-1-i][l] = k + i - l + w * 3;
}
}
if (n % 2 == 1) {
m[n/2][n/2] = k;
}
return m;
}
}
```