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

For example,
Given n = 3,

You should return the following matrix:

1
2
3
4
5
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
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
public class Solution {
public int[][] generateMatrix(int n) {
if (n < 1) return new int[0][0];
int[][] res = new int[n][n];
int num = 1;
int rowBegin = 0, colBegin = 0, rowEnd = n - 1, colEnd = n - 1;

while (rowBegin <= rowEnd && colBegin <= colEnd && num <= n * n) {
for (int i = colBegin; i <= colEnd; i++) {
res[rowBegin][i] = num++;
}
rowBegin++;
for (int i = rowBegin; i <= rowEnd; i++) {
res[i][colEnd] = num++;
}
colEnd--;
if (rowBegin <= rowEnd) {
for (int i = colEnd; i >= colBegin; i--) {
res[rowEnd][i] = num++;
}
}
rowEnd--;
if (colBegin <= colEnd) {
for (int i = rowEnd; i >= rowBegin; i--) {
res[i][colBegin] = num++;
}
}
colBegin++;
}
return res;
}
}