Skip to content

Commit bf1af76

Browse files
committed
spiralOrder solution
1 parent 1c75461 commit bf1af76

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

β€Žspiral-matrix/krokerdile.jsβ€Ž

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Time: O(m * n)
2+
// Space: O(1) + output array
3+
function spiralOrder(matrix) {
4+
const result = [];
5+
6+
let top = 0;
7+
let bottom = matrix.length - 1;
8+
let left = 0;
9+
let right = matrix[0].length - 1;
10+
11+
while (top <= bottom && left <= right) {
12+
// 1. μ™Ό β†’ 였
13+
for (let i = left; i <= right; i++) {
14+
result.push(matrix[top][i]);
15+
}
16+
top++;
17+
18+
// 2. μœ„ β†’ μ•„λž˜
19+
for (let i = top; i <= bottom; i++) {
20+
result.push(matrix[i][right]);
21+
}
22+
right--;
23+
24+
// 3. 였 β†’ μ™Ό
25+
if (top <= bottom) {
26+
for (let i = right; i >= left; i--) {
27+
result.push(matrix[bottom][i]);
28+
}
29+
bottom--;
30+
}
31+
32+
// 4. μ•„λž˜ β†’ μœ„
33+
if (left <= right) {
34+
for (let i = bottom; i >= top; i--) {
35+
result.push(matrix[i][left]);
36+
}
37+
left++;
38+
}
39+
}
40+
41+
return result;
42+
}

0 commit comments

Comments
Β (0)