Skip to main content

螺旋矩阵

题目

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

提示:
  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100
示例

54-spiral-order

输入: matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

输出: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]

题解

/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function (matrix) {
const res = []
let top = 0,
right = matrix[0].length - 1,
bottom = matrix.length - 1,
left = 0

while (top <= bottom && left <= right) {
for (let i = left; i <= right; i++) res.push(matrix[top][i])
top++

for (let i = top; i <= bottom; i++) res.push(matrix[i][right])
right--

if (top > bottom || left > right) break

for (let i = right; i >= left; i--) res.push(matrix[bottom][i])
bottom--

for (let i = bottom; i >= top; i--) res.push(matrix[i][left])
left++
}

return res
}