forked from JoshCrozier/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0054-spiral-matrix.js
43 lines (37 loc) · 917 Bytes
/
0054-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
/**
* 54. Spiral Matrix
* https://leetcode.com/problems/spiral-matrix/
* Difficulty: Medium
*
* Given an `m x n` `matrix`, return all elements of the `matrix` in spiral order.
*/
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
const output = [];
let top = 0;
let right = matrix[0].length - 1;
let bottom = matrix.length - 1;
let left = 0;
while (output.length < matrix.length * matrix[0].length) {
for (let i = left; i <= right; i++) {
output.push(matrix[top][i]);
}
top++;
for (let i = top; i <= bottom; i++) {
output.push(matrix[i][right]);
}
right--;
for (let i = right; top <= bottom && i >= left; i--) {
output.push(matrix[bottom][i]);
}
bottom--;
for (let i = bottom; left <= right && i >= top; i--) {
output.push(matrix[i][left]);
}
left++;
}
return output;
};