[LeetCode] Problem 59 - Spiral Matrix II

Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.

Example

Input: 3

Output:

1
2
3
4
5
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

Code

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
private int number = 0;

public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int start = 0;

while (start * 2 < n) {
generateMatrixHelper(matrix, n, start);
start++;
}

return matrix;
}

private void generateMatrixHelper(int[][] matrix, int n, int start) {
int endX = n - start - 1;
int endY = n - start - 1;

for (int i = start; i <= endX; i++)
matrix[start][i] = ++number;

if (endY > start) {
for (int i = start + 1; i <= endY; i++)
matrix[i][endX] = ++number;
}

if (endX > start && endY > start) {
for (int i = endX - 1; i >= start; i--)
matrix[endY][i] = ++number;
}

if (endX > start && endY > start + 1) {
for (int i = endY - 1; i > start; i--)
matrix[i][start] = ++number;
}
}