1. 题目描述

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:

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

示例 2:

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

2. 解题思路

对于这道题目,我们可以这样对二维数组进行遍历:
未命名文件 (1).png
在每一行每一列遍历的时候,不遍历到头,这样形成了一个个圆环,并且可以减少横向和竖向遍历之间的影响,经过一轮遍历之后,就四个边界都进行缩窄1,这样就可以往内部进行不断循环。

这里定义了四个边界:

  • 上边界 top : 0
  • 下边界 bottom : matrix.length - 1
  • 左边界 left : 0
  • 右边界 right : matrix[0].length - 1

需要注意的是,最后有可能剩余一行或者一列,它是无法构成圆环的,这种情况就要单独的处理:

  • 剩一行的情况:top == bottom && left < right
  • 剩一列的情况:top < bottom && left == right
  • 剩一项(也是一行/列)的情况:top == bottom && left == right

复杂度分析:

  • 时间复杂度:O(m*n),其中m、n 分别是矩阵的行数和列数,矩阵的每一个元素都要被访问一次。
  • 空间复杂度:O(1),除了输出数组以外,空间复杂度是常数。

    3. 代码实现

    1. /**
    2. * @param {number[][]} matrix
    3. * @return {number[]}
    4. */
    5. var spiralOrder = function(matrix) {
    6. if(!matrix.length) {
    7. return []
    8. }
    9. let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1
    10. const res = []
    11. while(top < bottom && left < right){
    12. for(let i = left; i < right; i++) res.push(matrix[top][i])
    13. for(let i = top; i < bottom; i++) res.push(matrix[i][right])
    14. for(let i = right; i > left; i--) res.push(matrix[bottom][i])
    15. for(let i = bottom; i > top; i--) res.push(matrix[i][left])
    16. right--
    17. top++
    18. bottom--
    19. left++
    20. }
    21. if(bottom === top){ // 剩下一行的情况
    22. for(let i = left; i <= right; i++){
    23. res.push(matrix[top][i])
    24. }
    25. }else if(left === right){ // 剩下一列的情况
    26. for(let i = top; i <= bottom; i++){
    27. res.push(matrix[i][left])
    28. }
    29. }
    30. return res
    31. };

    4. 提交结果

    image.png