-
Notifications
You must be signed in to change notification settings - Fork 1
/
spiral-matrix.ts
42 lines (34 loc) · 905 Bytes
/
spiral-matrix.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// 螺旋矩阵
// https://leetcode.cn/problems/spiral-matrix/
// INLINE ../../images/array/spiral-matrix.jpeg
export function spiralOrder (matrix: number[][]): number[] {
if (!matrix.length || !matrix[0].length) return []
const row = matrix.length
const col = matrix[0].length
const result: number[] = []
let left = 0
let right = col - 1
let top = 0
let bottom = row - 1
while (left <= right && top <= bottom) {
for (let i = left; i <= right; ++i) {
result.push(matrix[top][i])
}
for (let i = top + 1; i <= bottom; ++i) {
result.push(matrix[i][right])
}
if (left < right && top < bottom) {
for (let i = right - 1; i > left; --i) {
result.push(matrix[bottom][i])
}
for (let i = bottom; i > top; --i) {
result.push(matrix[i][left])
}
}
left++
right--
top++
bottom--
}
return result
}