Skip to content

Commit f6cf44e

Browse files
committed
5. Spiral Matrix
1 parent 8a42f7d commit f6cf44e

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

spiral-matrix/whewchews.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
function spiralOrder(matrix: number[][]): number[] {
2+
const rows = matrix.length;
3+
const cols = matrix[0].length;
4+
const total = rows * cols;
5+
let srow = 0; // start row
6+
let scol = 0;
7+
let erow = rows - 1; // end row
8+
let ecol = cols - 1;
9+
let count = 0;
10+
const ans: number[] = [];
11+
12+
while (count < total) {
13+
for (let i = scol; i <= ecol && count < total; i++) {
14+
ans.push(matrix[srow][i]);
15+
count++;
16+
}
17+
srow++;
18+
for (let i = srow; i <= erow && count < total; i++) {
19+
ans.push(matrix[i][ecol]);
20+
count++;
21+
}
22+
ecol--;
23+
for (let i = ecol; i >= scol && count < total; i--) {
24+
ans.push(matrix[erow][i]);
25+
count++;
26+
}
27+
erow--;
28+
for (let i = erow; i >= srow && count < total; i--) {
29+
ans.push(matrix[i][scol]);
30+
count++;
31+
}
32+
scol++;
33+
}
34+
35+
return ans;
36+
}
37+
38+
// TC: O(m*n)
39+
// SC: O(m*n)

0 commit comments

Comments
 (0)