-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path059.js
More file actions
49 lines (44 loc) · 1.08 KB
/
059.js
File metadata and controls
49 lines (44 loc) · 1.08 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
44
45
46
47
48
49
/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function(n) {
let matrix = [];
for(let i = 0; i < n; ++i) {
let row = [];
for(let j = 0; j < n; ++j) {
row.push(0);
}
matrix.push(row);
}
let leftOffset = 0;
let rightOffset = 0;
let topOffset = 0;
let bottomOffset = 0;
num = 1;
while(true) {
for(let i = leftOffset; i < n - rightOffset; ++i) {
matrix[topOffset][i] = num++;
}
++topOffset;
if (topOffset + bottomOffset >= n) break;
let col = n - 1 - rightOffset;
for(let i = topOffset; i < n - bottomOffset; ++i) {
matrix[i][col] = num++;
}
++rightOffset;
if (leftOffset + rightOffset >= n) break;
let row = n - 1 - bottomOffset;
for (let i = n - 1 - rightOffset; i >= leftOffset; --i) {
matrix[row][i] = num++;
}
++bottomOffset;
if (topOffset + bottomOffset >= n) break;
for (let i = n - 1 - bottomOffset; i >= topOffset; --i) {
matrix[i][leftOffset] = num++;
}
++leftOffset;
if (leftOffset + rightOffset >= n) break;
}
return matrix;
};