问题描述
Given an m x n matrix, return all elements of the matrix in spiral order.
Example :

1 2
| Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5]
|
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
解答
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 43 44 45 46
|
const spiralOrder = function (matrix) { if (!matrix || !matrix.length || !matrix[0].length) { return [] }
const rowLen = matrix.length - 1 const colLen = matrix[0].length - 1 let top = 0 let left = 0 let bottom = rowLen let right = colLen
const path = []
while (top <= bottom && left <= right) { for (let col = left; col <= right; col++) { path.push(matrix[top][col]) } for (let row = top + 1; row <= bottom; row++) { path.push(matrix[row][right]) } if (top < bottom && left < right) { for (let col = right - 1; col >= left; col--) { path.push(matrix[bottom][col]) } for (let row = bottom - 1; row > top; row--) { path.push(matrix[row][left]) } } top++ left++ bottom-- right-- } return path }
|