MediumArrays · Matrix

Spiral Matrix

Given an m × n matrix, return all of its elements in spiral order: along the top row, down the right side, back along the bottom, up the left side, then inward ring by ring.

[[1,2],[3,4]] → [1,2,4,3][[1,2,3],[4,5,6],[7,8,9]] → [1,2,3,6,9,8,7,4,5]

Try:
CALL
1 / 1

Code

The highlighted line runs next. The pill shows the live values in the running call.

Variables

The data structures the code is building

Matrix

The path grows one cell per append; corner numbers give the order

Time and space complexity

m rows, n columns. The highlighted row is the solution being traced.

Keyboard: ← → step, Space play or pause. Enter any matrix up to 6 × 6 like [[1,2,3],[4,5,6]]; all rows must be the same length.