## [LeetCode] 59. Spiral Matrix II

Example:

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

``` 1 /**
2  * @param {number} n
3  * @return {number[][]}
4  */
5 var generateMatrix = function (n) {
6     let res = Array(n).fill(0).map(() => Array(n).fill(0));
7     let rowBegin = 0;
8     let rowEnd = n - 1;
9     let colBegin = 0;
10     let colEnd = n - 1;
11     let num = 1;
12
13     while (rowBegin <= rowEnd && colBegin <= colEnd) {
14         // right
15         for (let i = colBegin; i <= colEnd; i++) {
16             res[rowBegin][i] = num++;
17         }
18         rowBegin++;
19
20         // down
21         for (let i = rowBegin; i <= rowEnd; i++) {
22             res[i][colEnd] = num++;
23         }
24         colEnd--;
25
26         // left
27         for (let i = colEnd; i >= colBegin; i--) {
28             res[rowEnd][i] = num++;
29         }
30         rowEnd--;
31
32         // up
33         for (let i = rowEnd; i >= rowBegin; i--) {
34             res[i][colBegin] = num++;
35         }
36         colBegin++;
37     }
38     return res;
39 };```