Skip to content

054.Spiral Matrix

难度: Easy

刷题内容

原题连接

  • https://leetcode.com/problems/search-insert-position/

内容描述

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

示例 1:

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

示例 2:

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

解题方案

思路 1 **- 时间复杂度: O(N)*- 空间复杂度: O(N)***

代码: 递归思路:

  1. 取矩阵的第一行
  2. 将矩阵逆时针反转90°
  3. 递归

终止条件: 矩阵为空 => 返回空矩阵 矩阵只剩下一行 => 返回这一行

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function(matrix) {
  if (!matrix || !matrix.length) {
    return matrix
  } else if (matrix.length === 1 && Array.isArray(matrix[0])) {
    return matrix[0]
  } else {
    return matrix.shift().concat(spiralOrder(rotate(matrix)))
  }
};


var rotate = function(matrix) {
  if (!matrix || !matrix.length) {
    return null
  }
  let newMatrix = []
  let m = matrix[0].length
  let n = matrix.length
  for (let y = m - 1; y >= 0; y--) {
    let newLine = []
    for (let x = n - 1; x >= 0; x--) {
      newLine.unshift(matrix[x][y])
    }
    newMatrix.push(newLine);
  }
  return newMatrix;
}

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组