Poison

59. Spiral Matrix II

Simulation
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];

// 注意此处巧妙利用了下一个格子是否为 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;
}
}
Simulation
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 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;
}
}
Reference

59. Spiral Matrix II