public class Solution {
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
int t= 0;
int cnt = 1;
while (t < n / 2) {
// top
for (int j = t; j < n - t - 1; j++) {
result[t][j] = cnt++;
}
// right
for (int i = t; i < n - t - 1; i++) {
result[i][n - t - 1] = cnt++;
}
// bottom
for (int j = n - t - 1; j > t; j--) {
result[n - t - 1][j] = cnt++;
}
// left
for (int i = n - t - 1; i > t; i--) {
result[i][t] = cnt++;
}
t++;
}
if (n % 2 == 1) {
result[n / 2][n / 2] = cnt;
}
return result;
}
}