Skip to content

Commit a41560b

Browse files
authored
Create 54-spiral-matrix.js
1 parent da611d6 commit a41560b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

54-spiral-matrix.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* @param {number[][]} matrix
3+
* @return {number[]}
4+
*/
5+
const spiralOrder = function(matrix) {
6+
const res = []
7+
let dir = 'top'
8+
while(matrix.length) {
9+
switch (dir) {
10+
case 'top':
11+
res.push(...matrix.shift())
12+
dir = 'right'
13+
break;
14+
case 'right':
15+
for(let i = 0; i < matrix.length - 1; ) {
16+
res.push(matrix[i].pop())
17+
if (matrix[i].length === 0) {
18+
matrix.splice(i, 1)
19+
} else {
20+
i++
21+
}
22+
}
23+
dir = 'bottom'
24+
break;
25+
case 'bottom':
26+
res.push(...matrix.pop().reverse())
27+
dir = 'left'
28+
break;
29+
case 'left':
30+
for(let i = matrix.length - 1; i >= 0; i--) {
31+
res.push(matrix[i].shift())
32+
if (matrix[i].length === 0) {
33+
matrix.splice(i, 1)
34+
}
35+
}
36+
dir = 'top'
37+
break;
38+
}
39+
}
40+
return res
41+
};

0 commit comments

Comments
 (0)