-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution.ts
40 lines (31 loc) · 803 Bytes
/
solution.ts
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
/*
* @lc app=leetcode id=59 lang=javascript
*
* [59] Spiral Matrix II
*/
// @lc code=start
/**
* @param {number} n
* @return {number[][]}
*/
const generateMatrix = (n: number): number[][] => {
// * ['52 ms', '92.84 %', '33.9 MB', '37.5 %']
// * if invalid
if (n < 1) return [];
// * ----------------
const result = Array.from({ length: n }, () => Array(n));
let count = 0;
let r = 0;
let c = -1;
let step = n;
while (step > 0) {
for (let i = 0; i < step; i++) result[r][++c] = ++count;
for (let i = 0; i < step - 1; i++) result[++r][c] = ++count;
for (let i = 0; i < step - 1; i++) result[r][--c] = ++count;
for (let i = 0; i < step - 2; i++) result[--r][c] = ++count;
step -= 2;
}
return result;
};
// @lc code=end
export { generateMatrix };