https://leetcode-cn.com/problems/spiral-matrix/ 数组

基础

【54】螺旋矩阵:中等 - 图1

  1. function spiralOrder(matrix: number[][]): number[] {
  2. const result: number[] = [];
  3. let top = 0
  4. let bottom = matrix.length - 1
  5. let left = 0
  6. let right = matrix[0] ? matrix[0].length - 1 : 0
  7. while(top <= bottom && left <= right) {
  8. // 1 * N only →
  9. for(let i = left; i <= right && top === bottom; i++) {
  10. result.push(matrix[top][i])
  11. }
  12. // N * 1 (N > 1) only ↓
  13. for(let i = top; i <= bottom && right === top && top !== bottom; i++) {
  14. result.push(matrix[i][right])
  15. }
  16. // →
  17. for(let i = left; i < right && bottom > top; i++) {
  18. result.push(matrix[top][i])
  19. }
  20. // ↓
  21. for(let i = top; i < bottom && right > top; i++) {
  22. result.push(matrix[i][right])
  23. }
  24. // ←
  25. for(let i = right; i > left && bottom > top; i--) {
  26. result.push(matrix[bottom][i])
  27. }
  28. // ↑
  29. for(let i = bottom; i > top && right > top; i--) {
  30. result.push(matrix[i][left])
  31. }
  32. top++
  33. bottom--
  34. left++
  35. right--
  36. }
  37. return result
  38. };