-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathSpiralMatrixII.js
96 lines (81 loc) · 2.08 KB
/
SpiralMatrixII.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
*
* For example,
* Given n = 3,
*
* You should return the following matrix:
* [
* [ 1, 2, 3 ],
* [ 8, 9, 4 ],
* [ 7, 6, 5 ]
* ]
*
* Accepted.
*/
/**
* @param {number} n
* @return {number[][]}
*/
let generateMatrix = function (n) {
if (n <= 0) {
return [];
}
if (n === 1) {
return [[1]];
}
let matrix = new Array(n);
for (let i = 0; i < n; i++) {
matrix[i] = new Array(n);
for (let j = 0; j < n; j++) {
matrix[i][j] = 0;
}
}
let centerX = n % 2 === 0 ? parseInt((n - 1) / 2) : parseInt(n / 2);
let centerY = n % 2 === 0 ? parseInt((n - 1) / 2) : parseInt(n / 2);
let i = 0, j = 0, depth = 0, result = 1;
while (i <= centerX && j <= centerY && depth <= centerX && depth <= centerY) {
for (j = depth, i = depth; j < matrix[0].length - depth; j++) {
if (matrix[i][j] === 0) {
matrix[i][j] = result++;
}
}
for (j--, i++; i < matrix.length - depth; i++) {
if (matrix[i][j] === 0) {
matrix[i][j] = result++;
}
}
for (i--, j--; j >= depth; j--) {
if (matrix[i][j] === 0) {
matrix[i][j] = result++;
}
}
for (j++, i--; i > depth; i--) {
if (matrix[i][j] === 0) {
matrix[i][j] = result++;
}
}
depth++;
}
return matrix;
};
if (generateMatrix(0).toString() === [].toString()) {
console.log("pass")
} else {
console.error("failed")
}
if (generateMatrix(1).toString() === [[1]].toString()) {
console.log("pass")
} else {
console.error("failed")
}
if (generateMatrix(2).toString() === [[1, 2], [4, 3]].toString()) {
console.log("pass")
} else {
console.error("failed")
}
if (generateMatrix(4).toString() === [[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]].toString()) {
console.log("pass")
} else {
console.error("failed")
}