59. Spiral Matrix II 发表于 2022-01-26 Simulation12345678910111213141516171819202122232425262728class 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]; // 注意此处巧妙利用了下一个格子是否为 0 来判断是否到达了已经填充过的边界 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; }} Simulation12345678910111213141516171819202122232425262728class Solution { public int[][] generateMatrix(int n) { int[][] matrix = new int[n][n]; int topIndex = 0, downIndex = n - 1, leftIndex = 0, rightIndex = n - 1; int num = 1, maxNum = n * n; while (num <= maxNum) { for (int j = leftIndex; j <= rightIndex; j++) { matrix[topIndex][j] = num++; } topIndex++; for (int i = topIndex; i <= downIndex; i++) { matrix[i][rightIndex] = num++; } rightIndex--; for (int j = rightIndex; j >= leftIndex; j--) { matrix[downIndex][j] = num++; } downIndex--; for (int i = downIndex; i >= topIndex; i--) { matrix[i][leftIndex] = num++; } leftIndex++; } return matrix; }} Reference59. Spiral Matrix II