难度:简单

    题目描述:
    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字

    示例:

    1. 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
    2. 输出:[1,2,3,6,9,8,7,4,5]

    解题思路:
    image.png

    1. var spiralOrder = function (matrix) {
    2. if (matrix.length == 0) return []
    3. const res = []
    4. let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1
    5. const size = matrix.length * matrix[0].length
    6. while (res.length !== size) { // 仍未遍历结束
    7. for (let i = left; i <= right; i++) res.push(matrix[top][i])
    8. top++
    9. for (let i = top; i <= bottom; i++) res.push(matrix[i][right])
    10. right--
    11. if (res.length === size) break // 遍历结束
    12. for (let i = right; i >= left; i--) res.push(matrix[bottom][i])
    13. bottom--
    14. for (let i = bottom; i >= top; i--) res.push(matrix[i][left])
    15. left++
    16. }
    17. return res
    18. };
    1. var spiralOrder = function (matrix) {
    2. if (matrix.length == 0) return []
    3. const res = []
    4. let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1
    5. while (top <= bottom && left <= right) {
    6. for (let i = left; i <= right; i++) res.push(matrix[top][i])
    7. top++
    8. for (let i = top; i <= bottom; i++) res.push(matrix[i][right])
    9. right--
    10. if (top > bottom || left > right) break
    11. for (let i = right; i >= left; i--) res.push(matrix[bottom][i])
    12. bottom--
    13. for (let i = bottom; i >= top; i--) res.push(matrix[i][left])
    14. left++
    15. }
    16. return res
    17. };