给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

思路

  1. 引入变量 top = 0, bottom = m - 1, left = 0, right = n - 1
  2. 「一圈」包括了 toRight, toBottom, toLeft, toTop 动作,直到 top > bottom 或 left > right
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
var spiralOrder = function (matrix) {
const M = matrix.length
const N = matrix[0].length
let [top, bottom, left, right] = [0, M - 1, 0, N - 1]
const items = []
while (top <= bottom && left <= right) {
for (let j = left; j <= right; ++j) {
items.push(matrix[top][j])
}
++top
for (let i = top; i <= bottom; ++i) {
items.push(matrix[i][right])
}
--right
if (top > bottom || left > right) {
break
}
for (let j = right; j >= left; --j) {
items.push(matrix[bottom][j])
}
--bottom
for (let i = bottom; i >= top; --i) {
items.push(matrix[i][left])
}
++left
}
return items
}