leetcode 59. spiral matrix ii

59. Spiral Matrix II

Difficulty: Medium

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

Example:

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

Solution

Language: Java

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
class  {
public int[][] generateMatrix(int n) {
if (n < 0) {
return null;
}
if (n == 0) {
return new int[][]{};
}
int[][] result = new int[n][n];

int start = 0;
int end = n - 1;
int x = 0, y = -1;
int cur = 1;
while (start <= end) {
while(y + 1 <= end) {
result[x][++y] = cur++;
}
while(x + 1 <= end) {
result[++x][y] = cur++;
}
while(y - 1 >= start) {
result[x][--y] = cur++;
}
start++;
while(x - 1 >= start) {
result[--x][y] = cur++;
}
end--;
}
return result;
}
}