https://leetcode-cn.com/problems/spiral-matrix/
点击查看【bilibili】

题目

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

示例

54. 螺旋矩阵 Spiral Matrix - 图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]

54. 螺旋矩阵 Spiral Matrix - 图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]

解答

image.png
1.如果数组为空,返回空数组
2.定义4个边界以及当前方向(direction)
3.当左边界小于等于右边界,且上边界小等于下边界时,执行 while循环:
按照右,下,左,上的顺序,依欠将路径上的字符添加到结果里
4. while循环结束后,返回结果
image.png
image.png
为什么left<=right && top <= bottom ?
考虑边界问题
image.png

答案

  1. var spiralOrder = function (matrix) {
  2. if (matrix.length === 0) return [];
  3. let left = 0
  4. let right = matrix[0].length - 1
  5. let top = 0
  6. let bottom = matrix.length - 1
  7. let direction = 'right'
  8. let result = []
  9. /**
  10. [ 1, 2, 3 ],
  11. [ 4, 5, 6 ],
  12. [ 7, 8, 9 ]
  13. */
  14. while (left <= right && top <= bottom) {
  15. if (direction === 'right') {
  16. for (let i = left; i <= right; i++) {
  17. result.push(matrix[top][i])
  18. }
  19. top++
  20. direction = 'down'
  21. } else if (direction === 'down') {
  22. for (let i = top; i <= bottom; i++) {
  23. result.push(matrix[i][right])
  24. }
  25. right--
  26. direction = 'left'
  27. } else if (direction === 'left') {
  28. for (let i = right; i >= left; i--) {
  29. result.push(matrix[bottom][i])
  30. }
  31. bottom--
  32. direction = 'top'
  33. } else if (direction === 'top') {
  34. for (let i = bottom; i >= top; i--) {
  35. result.push(matrix[i][left])
  36. }
  37. left++
  38. direction = 'right'
  39. }
  40. }
  41. return result
  42. };