noodleProblems/
Spiral Matrix
#62

Spiral Matrix

AlgorithmmediumArrayMatrixSimulation

Given an m x n matrix, return all of its elements in **spiral order**: start at the top-left, move right across the top row, down the right column, left across the bottom row, up the left column, and continue spiralling inward until every element is visited.

Example cases

  • 3x3
    in matrix =
    123
    456
    789
    out [1,2,3,6,9,8,7,4,5]
    Right across the top, down the right edge, left along the bottom, up the left edge, then the center.
  • 3x4
    in matrix =
    1234
    5678
    9101112
    out [1,2,3,4,8,12,11,10,9,5,6,7]
  • single row
    in matrix =
    123
    out [1,2,3]

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100
Saved
matrix =
[[1,2,3],[4,5,6],[7,8,9]]