-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.js
More file actions
43 lines (38 loc) · 1.02 KB
/
solution.js
File metadata and controls
43 lines (38 loc) · 1.02 KB
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) {
let matrix = []
for (let i = 0; i < n; i++) {
matrix.push(new Array(n));
}
let i = j = 0,
topLimit = leftLimit = 0,
bottomLimit = rightLimit = n - 1,
xDirection = 1,
yDirection = 0
for (let v = 1; v <= Math.pow(n, 2); v++) {
matrix[i][j] = v
if (j + xDirection > rightLimit) {
topLimit = i + 1
xDirection = 0
yDirection = 1
} else if (i + yDirection > bottomLimit) {
rightLimit = j - 1
xDirection = -1
yDirection = 0
} else if (j + xDirection < leftLimit) {
bottomLimit = i - 1
xDirection = 0
yDirection = -1
} else if (i + yDirection < topLimit) {
leftLimit = j + 1
xDirection = 1
yDirection = 0
}
i += yDirection
j += xDirection
}
return matrix
};