Skip to content

Commit 36743b0

Browse files
committed
Add week 6 solutions: spiral-matrix
1 parent 36e7cf3 commit 36743b0

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

spiral-matrix/gitsunmin.ts

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

0 commit comments

Comments
 (0)