public class Solution {
public int[][] generateMatrix(int n) {
if (n < 1) return new int[0][0];
int[][] res = new int[n][n];
int left = 0, right = n - 1, up = 0, down = n - 1;
int k = 1;
while(true) {
for (int i = left; i <= right; i++) {
res[up][i] = k++;
}
if (++up > down) break;
for (int i = up; i <= down; i++) {
res[i][right] = k++;
}
if(--right < left) break;
for (int i = right; i >= left; i--) {
res[down][i] = k++;
}
if (--down < up) break;
for (int i = down; i >= up; i--) {
res[i][left] = k++;
}
if (++left > right) break;
}
return res;
}
}