Skip to content

Commit 94197dc

Browse files
committedSep 18, 2021
Add solution #54
1 parent 0148348 commit 94197dc

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
31|[Next Permutation](./0031-next-permutation.js)|Medium|
1212
36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium|
1313
43|[Multiply Strings](./0043-multiply-strings.js)|Medium|
14+
54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium|
1415
58|[Length of Last Word](./0058-length-of-last-word.js)|Easy|
1516
66|[Plus One](./0066-plus-one.js)|Easy|
1617
67|[Add Binary](./0067-add-binary.js)|Easy|

‎solutions/0054-spiral-matrix.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 54. Spiral Matrix
3+
* https://leetcode.com/problems/spiral-matrix/
4+
* Difficulty: Medium
5+
*
6+
* Given an `m x n` `matrix`, return all elements of the `matrix` in spiral order.
7+
*/
8+
9+
/**
10+
* @param {number[][]} matrix
11+
* @return {number[]}
12+
*/
13+
var spiralOrder = function(matrix) {
14+
const output = [];
15+
let top = 0;
16+
let right = matrix[0].length - 1;
17+
let bottom = matrix.length - 1;
18+
let left = 0;
19+
20+
while (output.length < matrix.length * matrix[0].length) {
21+
for (let i = left; i <= right; i++) {
22+
output.push(matrix[top][i]);
23+
}
24+
top++;
25+
26+
for (let i = top; i <= bottom; i++) {
27+
output.push(matrix[i][right]);
28+
}
29+
right--;
30+
31+
for (let i = right; top <= bottom && i >= left; i--) {
32+
output.push(matrix[bottom][i]);
33+
}
34+
bottom--;
35+
36+
for (let i = bottom; left <= right && i >= top; i--) {
37+
output.push(matrix[i][left]);
38+
}
39+
left++;
40+
}
41+
42+
return output;
43+
};

0 commit comments

Comments
 (0)
Please sign in to comment.