Skip to content

Commit 7dd2a8e

Browse files
committed
spiral order solution
1 parent 12b63ca commit 7dd2a8e

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

spiral-matrix/radiantchoi.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
function spiralOrder(matrix: number[][]): number[] {
2+
let x = 0;
3+
let y = 0;
4+
5+
let result: number[] = [];
6+
const threshold = matrix.length * matrix[0].length
7+
8+
let direction = 0;
9+
const dx = [0, 1, 0, -1];
10+
const dy = [1, 0, -1, 0];
11+
let visited = Array.from({ length: matrix.length }, () => Array(matrix[0].length).fill(false))
12+
13+
while (true) {
14+
if (result.length >= threshold) {
15+
break;
16+
}
17+
18+
result.push(matrix[x][y]);
19+
visited[x][y] = true
20+
21+
const nx = x + dx[direction]
22+
const ny = y + dy[direction]
23+
24+
if (nx < 0 || nx >= matrix.length || ny < 0 || ny >= matrix[0].length || visited[nx][ny]) {
25+
direction++;
26+
27+
if (direction > 3) {
28+
direction = 0;
29+
}
30+
31+
x += dx[direction];
32+
y += dy[direction];
33+
} else {
34+
x = nx;
35+
y = ny;
36+
}
37+
}
38+
39+
return result;
40+
};

0 commit comments

Comments
 (0)