~/problems / Simulation & OOP design / Simulation

Spiral Matrix

easy ~20 min

Write spiral_order(matrix) that returns all elements of an m x n matrix in clockwise spiral order: along the top row left to right, down the right column, along the bottom row right to left, up the left column, then the same on the next ring inward, until every element is visited once.

  • 1 <= m, n <= 50; the matrix is a list of equal-length rows.
  • Watch non-square matrices, where a single row or column is left in the middle: every element must appear exactly once.
spiral_order([[1, 2, 3],
              [4, 5, 6]])          # [1, 2, 3, 6, 5, 4]
spiral_order([[1], [2], [3]])      # [1, 2, 3]
Show hint

track the edges of the part you haven't visited yet and shrink one after walking each side. Before walking the bottom row or the left column, check that there's still something left to walk.

Topic: Simulation. Model the process exactly; watch simultaneous updates and direction arithmetic.

0:00
Ctrl ' run · Ctrl ↵ submit
esc