-
Notifications
You must be signed in to change notification settings - Fork 7
/
54-Spiral-Matrix.js
45 lines (38 loc) · 1.26 KB
/
54-Spiral-Matrix.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
// 54. Spiral Matrix [Medium]
// https://leetcode.com/problems/spiral-matrix/
/**
* @param {number[][]} matrix
* @return {number[]}
*/
const spiralOrder = (matrix) => {
if (matrix.length === 1) return matrix[0];
if (matrix[0].length === 1) return matrix.flat();
const travel = [];
let leftBoundary = 0;
let rightBoundary = matrix[0].length - 1;
let upperBoundary = 0;
let lowerBoundary = matrix.length - 1;
while (leftBoundary <= rightBoundary && upperBoundary <= lowerBoundary) {
for (let i = leftBoundary; i <= rightBoundary; i++) {
travel.push(matrix[upperBoundary][i]);
}
upperBoundary++;
for (let i = upperBoundary; i <= lowerBoundary; i++) {
travel.push(matrix[i][rightBoundary]);
}
rightBoundary--;
if (upperBoundary <= lowerBoundary) {
for (let i = rightBoundary; i >= leftBoundary; i--) {
travel.push(matrix[lowerBoundary][i]);
}
lowerBoundary--;
}
if (leftBoundary <= rightBoundary) {
for (let i = lowerBoundary; i >= upperBoundary; i--) {
travel.push(matrix[i][leftBoundary]);
}
leftBoundary++;
}
}
return travel;
};