-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
36 lines (31 loc) · 849 Bytes
/
Copy pathmain.js
File metadata and controls
36 lines (31 loc) · 849 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
/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function(n) {
const ans = Array.from({ length: n }, () => Array.from({ length: n }))
let left = 0
let right = n - 1
let top = 0
let bottom = n - 1
let cnt = 0
while (left < right && top < bottom) {
for (let i = left; i < right; i++) ans[top][i] = (++cnt)
for (let i = top; i < bottom; i++) ans[i][right] = (++cnt)
for (let i = right; i > left; i--) ans[bottom][i] = (++cnt)
for (let i = bottom; i > top; i--) ans[i][left] = (++cnt)
left++
top++
right--
bottom--
}
if (left === right) {
for (let i = top; i <= bottom; i++) ans[i][left] = (++cnt)
} else if (top === bottom) {
for (let i = left; i <= right; i++) ans[top][i] = (++cnt)
}
return ans
};
if (process.env.LZS) {
console.log(generateMatrix(3))
}