Skip to content

Commit 442768a

Browse files
committed
Add JS spiral matrix LC medium solution
1 parent 119cc02 commit 442768a

File tree

2 files changed

+93
-0
lines changed

2 files changed

+93
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*
2+
https://leetcode.com/problems/spiral-matrix/
3+
4+
Given an m x n matrix, return all elements of the matrix in spiral order.
5+
6+
Example 1:
7+
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
8+
Output: [1,2,3,6,9,8,7,4,5]
9+
10+
Example 2:
11+
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
12+
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
13+
14+
Constraints:
15+
m == matrix.length
16+
n == matrix[i].length
17+
1 <= m, n <= 10
18+
-100 <= matrix[i][j] <= 100
19+
*/
20+
21+
const RIGHT = "right";
22+
const DOWN = "down";
23+
const LEFT = "left";
24+
const UP = "up";
25+
26+
const spiralOrder = (matrix) => {
27+
const result = [];
28+
// Can be: "right", "down", "left", "up"
29+
let direction = RIGHT;
30+
let offset = 0;
31+
let x = 0;
32+
let y = 0;
33+
34+
while (true) {
35+
result.push(matrix[y][x]);
36+
37+
if (direction == RIGHT) {
38+
if (x < matrix[0].length - 1 - offset) {
39+
x += 1;
40+
} else {
41+
direction = DOWN;
42+
y += 1;
43+
}
44+
} else if (direction === DOWN) {
45+
if (y < matrix.length - 1 - offset) {
46+
y += 1;
47+
} else {
48+
direction = LEFT;
49+
x -= 1;
50+
}
51+
} else if (direction === LEFT) {
52+
if (x > 0 + offset) {
53+
x -= 1;
54+
} else {
55+
direction = UP;
56+
offset += 1;
57+
y -= 1;
58+
}
59+
} else {
60+
if (y > 0 + offset) {
61+
y -= 1;
62+
} else {
63+
direction = RIGHT;
64+
x += 1;
65+
}
66+
}
67+
68+
if (result.length === matrix.length * matrix[0].length) {
69+
break;
70+
}
71+
}
72+
73+
return result;
74+
};
75+
76+
module.exports = { spiralOrder };
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
const { spiralOrder } = require("./spiralMatrix");
2+
3+
describe("spiralOrder", () => {
4+
it("returns the correct spiral order for a list with one array of one integer", () => {
5+
const result = spiralOrder([[0]]);
6+
expect(result).toEqual([0]);
7+
});
8+
9+
it("returns the correct spiral order for a 2D matrix", () => {
10+
const result = spiralOrder([
11+
[1, 2, 3],
12+
[4, 5, 6],
13+
[7, 8, 9],
14+
]);
15+
expect(result).toEqual([1, 2, 3, 6, 9, 8, 7, 4, 5]);
16+
});
17+
});

0 commit comments

Comments
 (0)