Skip to content

Commit 54bab01

Browse files
committed
spiral matrix solution
1 parent 61e16db commit 54bab01

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

spiral-matrix/hyer0705.ts

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

0 commit comments

Comments
 (0)