public static int[][] generateMatrix(int n) { int[][] ans = newint[n][n];
int num = 0; int left = 0; int right = n - 1; int top = 0; int bottom = n - 1; while (left <= right && top <= bottom) { for (int column = left; column <= right; column++) { ans[top][column] = ++num; } for (introw = top + 1; row <= bottom; row++) { ans[row][right] = ++num; }
if (left < right && top < bottom) { for (int column = right - 1; column > left; column--) { ans[bottom][column] = ++num; } for (introw = bottom; row > top; row--) { ans[row][left] = ++num; } } left++; right--; bottom--; top++; }
return ans; }
public static void main(String[] args) { print(generateMatrix(3));