1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { public int[][] generateMatrix(int n) { int[][] matrix = new int[n][n];
int[][] directions = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; int directionIndex = 0;
int topIndex = 0, downIndex = n - 1, leftIndex = 0, rightIndex = n - 1;
int i = 0, j = 0; for (int k = 1; k <= n * n; k++) { matrix[i][j] = k;
int nextI = i + directions[directionIndex][0]; int nextJ = j + directions[directionIndex][1];
if (nextJ > rightIndex || nextI > downIndex || nextJ < leftIndex || nextI < topIndex || matrix[nextI][nextJ] != 0) { directionIndex = (directionIndex + 1) % 4; }
i += directions[directionIndex][0]; j += directions[directionIndex][1]; }
return matrix; } }
|