Skip to content

Commit c5e0e20

Browse files
committed
Create 54.螺旋矩阵.js
1 parent 9440022 commit c5e0e20

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

54.螺旋矩阵.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* @param {number[][]} matrix
3+
* @return {number[]}
4+
*/
5+
var spiralOrder = function(matrix) {
6+
if (matrix.length < 1) {
7+
return [];
8+
}
9+
const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
10+
let d = 0;
11+
let x = 0, y = -1;
12+
let count = matrix.length * matrix[0].length;
13+
let result = [];
14+
while (count) {
15+
const nextX = x + directions[d][0];
16+
const nextY = y + directions[d][1];
17+
if (matrix[nextX] && matrix[nextX][nextY] !== undefined) {
18+
result.push(matrix[nextX][nextY]);
19+
matrix[nextX][nextY] = undefined;
20+
count--;
21+
x = nextX;
22+
y = nextY;
23+
} else {
24+
d = (d + 1) % directions.length;
25+
}
26+
}
27+
return result;
28+
};
29+
30+
console.log(spiralOrder(
31+
[
32+
[1, 2]
33+
]
34+
));

0 commit comments

Comments
 (0)