Skip to content

Commit 1fa6b7d

Browse files
committed
add Spiral Matrix solution
1 parent 41380d2 commit 1fa6b7d

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

spiral-matrix/HoonDongKang.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* [Problem]: [54] Spiral Matrix
3+
* (https://leetcode.com/problems/spiral-matrix/description/)
4+
*/
5+
function spiralOrder(matrix: number[][]): number[] {
6+
const result: number[] = [];
7+
let top = 0;
8+
let bottom = matrix.length - 1;
9+
let left = 0;
10+
let right = matrix[0].length - 1;
11+
12+
while (top <= bottom && left <= right) {
13+
for (let i = left; i <= right; i++) {
14+
result.push(matrix[top][i]);
15+
}
16+
top++;
17+
18+
for (let i = top; i <= bottom; i++) {
19+
result.push(matrix[i][right]);
20+
}
21+
right--;
22+
23+
if (top <= bottom) {
24+
for (let i = right; i >= left; i--) {
25+
result.push(matrix[bottom][i]);
26+
}
27+
bottom--;
28+
}
29+
30+
if (left <= right) {
31+
for (let i = bottom; i >= top; i--) {
32+
result.push(matrix[i][left]);
33+
}
34+
left++;
35+
}
36+
}
37+
38+
return result;
39+
}

0 commit comments

Comments
 (0)