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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int value = 1;

int rowStartIndex = 0, rowEndIndex = n - 1, colStartIndex = 0, colEndIndex = n - 1;
while (true) {
// left -> right
for (int colIndex = colStartIndex; colIndex <= colEndIndex; colIndex++) {
matrix[rowStartIndex][colIndex] = value++;
}
if (++rowStartIndex > rowEndIndex) {
break;
}

// top -> bottom
for (int rowIndex = rowStartIndex; rowIndex <= rowEndIndex; rowIndex++) {
matrix[rowIndex][colEndIndex] = value++;
}
if (--colEndIndex < colStartIndex) {
break;
}

// right -> left
for (int colIndex = colEndIndex; colIndex >= colStartIndex; colIndex--) {
matrix[rowEndIndex][colIndex] = value++;
}
if (--rowEndIndex < rowStartIndex) {
break;
}

// bottom -> top
for (int rowIndex = rowEndIndex; rowIndex >= rowStartIndex; rowIndex--) {
matrix[rowIndex][colStartIndex] = value++;
}
if (++colStartIndex > colEndIndex) {
break;
}
}

return matrix;
}
}

References

59. Spiral Matrix II