forked from tangweikun/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
43 lines (36 loc) · 831 Bytes
/
index.ts
File metadata and controls
43 lines (36 loc) · 831 Bytes
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
41
42
43
// HELP:
export const generateMatrix = (n: number) => {
const res = Array.from({ length: n }, _ => Array(n).fill(0))
let rowU = 0
let rowD = n - 1
let colL = 0
let colR = n - 1
let fill = 1 // used to fill matrix, will be updated after each fill
while (rowU <= rowD && colL <= colR) {
// fill top row
for (let i = colL; i <= colR; i++) {
res[rowU][i] = fill++
}
rowU++
// fill right col
for (let i = rowU; i <= rowD; i++) {
res[i][colR] = fill++
}
colR--
// fill bottom row
if (rowU <= rowD) {
for (let i = colR; i >= colL; i--) {
res[rowD][i] = fill++
}
rowD--
}
// fill left col
if (colL <= colR) {
for (let i = rowD; i >= rowU; i--) {
res[i][colL] = fill++
}
colL++
}
}
return res
}