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

示例 1:
螺旋矩阵 - 图1

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
螺旋矩阵 - 图2

输入: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]

提示:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100

思路:


  1. ```javascript var spiralOrder = function (matrix) { if (matrix.length === 0) return [] const res = [] let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1 while (top < bottom && left < right) { for (let i = left; i < right; i++) res.push(matrix[top][i]) // 上层 for (let i = top; i < bottom; i++) res.push(matrix[i][right]) // 右层 for (let i = right; i > left; i—) res.push(matrix[bottom][i])// 下层 for (let i = bottom; i > top; i—) res.push(matrix[i][left]) // 左层 right— top++ bottom— left++ // 四个边界同时收缩,进入内层 } if (top === bottom) // 剩下一行,从左到右依次添加 for (let i = left; i <= right; i++) res.push(matrix[top][i]) else if (left === right) // 剩下一列,从上到下依次添加 for (let i = top; i <= bottom; i++) res.push(matrix[i][left]) return res };
  1. <a name="OxtIy"></a>
  2. ## 更简洁的方法
  3. 1. 一次push一行/列
  4. 1. **push完马上收缩边界,并判断是否超出边界**
  5. 1. 一旦超出边界就break
  6. 3. 这样就不用最后再来考虑有没有剩下的
  7. ```javascript
  8. const spiralOrder = function (matrix) {
  9. if (matrix.length === 0) return [];
  10. let top = 0, bottom = matrix.length - 1,
  11. left = 0, right = matrix[0].length - 1;
  12. let res = [];
  13. while (true) {
  14. for (let i = left; i <= right; i++) res.push(matrix[top][i]);
  15. if (++top > bottom) break;
  16. for (let i = top; i <= bottom; i++) res.push(matrix[i][right]);
  17. if (--right < left) break;
  18. for (let i = right; i >= left; i--) res.push(matrix[bottom][i]);
  19. if (--bottom < top) break;
  20. for (let i = bottom; i >= top; i--) res.push(matrix[i][left]);
  21. if (++left > right) break;
  22. }
  23. return res;
  24. }
const spiralOrder = function (matrix) {
  if (matrix.length === 0) return [];
  let top = 0, bottom = matrix.length - 1,
    left = 0, right = matrix[0].length - 1;
  let res = [];
  while (true) {
    for (let i = left; i <= right; i++) res.push(matrix[top][i]);
    if (++top > bottom) break;

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

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

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