Editor

Spiral Walk Through a Matrix

#84 · Simulation · Intermediate · 70 XP · about 14 min

Start at the top-left corner of a grid of numbers and walk clockwise around the outside: right along the top row, down the right column, left along the bottom row and up the left column. Then do the same with the ring inside it, and keep going until every cell has been visited exactly once.

Write spiral_order(matrix) that returns the values in the order you visit them. matrix is a list of rows that all have the same length, and it can be empty.

Examples

spiral_order([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])
# returns [1, 2, 3, 6, 9, 8, 7, 4, 5]

spiral_order([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12]])
# returns [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]

spiral_order([[1], [2], [3]])    # returns [1, 2, 3]

Constraints

  • 0 <= number of rows, number of columns <= 100
  • The grid does not have to be square, so the innermost ring can be a single row or a single column

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.