Skip to content

Commit ad9655e

Browse files
committed
Added spiral-matrix solution
1 parent 743028c commit ad9655e

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

spiral-matrix/nhistory.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
var spiralOrder = function (matrix) {
2+
// Edge case
3+
if (matrix.length === 0) return [];
4+
5+
let result = [];
6+
let rowStart = 0,
7+
rowEnd = matrix.length - 1;
8+
let colStart = 0,
9+
colEnd = matrix[0].length - 1;
10+
11+
while (rowStart <= rowEnd && colStart <= colEnd) {
12+
// Traverse right
13+
for (let col = colStart; col <= colEnd; col++) {
14+
result.push(matrix[rowStart][col]);
15+
}
16+
rowStart++;
17+
18+
// Traverse down
19+
for (let row = rowStart; row <= rowEnd; row++) {
20+
result.push(matrix[row][colEnd]);
21+
}
22+
colEnd--;
23+
24+
// Traverse left (check if rowStart <= rowEnd to avoid duplicates)
25+
if (rowStart <= rowEnd) {
26+
for (let col = colEnd; col >= colStart; col--) {
27+
result.push(matrix[rowEnd][col]);
28+
}
29+
rowEnd--;
30+
}
31+
32+
// Traverse up (check if colStart <= colEnd to avoid duplicates)
33+
if (colStart <= colEnd) {
34+
for (let row = rowEnd; row >= rowStart; row--) {
35+
result.push(matrix[row][colStart]);
36+
}
37+
colStart++;
38+
}
39+
}
40+
41+
return result;
42+
};
43+
44+
// TC: O(m*n)
45+
// SC: O(m*n)

0 commit comments

Comments
 (0)