-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy path0054.SpiralMatrix.js
43 lines (39 loc) · 983 Bytes
/
0054.SpiralMatrix.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
var spiralOrder = function (matrix) {
if (matrix.length === 0) {
return [];
}
let top = 0;
let bottom = matrix.length - 1;
let left = 0;
let right = matrix[0].length - 1;
let direction = "right";
let result = [];
while (left <= right && top <= bottom) {
if (direction === "right") {
for (let i = left; i <= right; i++) {
result.push(matrix[top][i]);
}
top++;
direction = "down";
} else if (direction === "down") {
for (let i = top; i <= bottom; i++) {
result.push(matrix[i][right]);
}
right--;
direction = "left";
} else if (direction === "left") {
for (let i = right; i >= left; i--) {
result.push(matrix[bottom][i]);
}
bottom--;
direction = "top";
} else if (direction === "top") {
for (let i = bottom; i >= top; i--) {
result.push(matrix[i][left]);
}
left++;
direction = "right";
}
}
return result;
};