-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.js
43 lines (40 loc) · 1.02 KB
/
solution.js
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
/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function (n) {
const arr = Array.apply(null, {
length: n,
}).map(() => new Array(n));
let top = 0;
let right = n;
let bottom = n;
let left = 0;
let direction = 0;
let count = 0;
while (left < right && top < bottom) {
if (direction === 0) {
for (let i = left; i < right; i++) {
arr[top][i] = ++count;
}
top++;
} else if (direction === 1) {
right--;
for (let i = top; i < bottom; i++) {
arr[i][right] = ++count;
}
} else if (direction === 2) {
bottom--;
for (let i = right - 1; i >= left; i--) {
arr[bottom][i] = ++count;
}
} else {
for (let i = bottom - 1; i >= top; i--) {
arr[i][left] = ++count;
}
left++;
}
direction = (direction + 1) % 4;
}
return arr;
};