You are given matrix, a grid of integers with m rows and n columns.
Return all of its values in spiral order: start at the top-left corner, go right along the top row, down the right column, left along the bottom row and up the left column, then carry on the same way round the part not yet read, until every value is listed exactly once.
Example 1
- Input
- matrix = [[1, 2, 3, 4], [10, 11, 12, 5], [9, 8, 7, 6]]
- Output
- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Example 2
- Input
- matrix = [[1, 2], [3, 4], [5, 6]]
- Output
- [1, 2, 4, 6, 5, 3]
Constraints
- 1 ≤ m, n ≤ 20
- −1000 ≤
matrix[r][c]≤ 1000
Show the pattern
Math and matrices
It is index arithmetic on a 2D layout: walk round the outer ring with four bounds (top, bottom, left, right), pull each bound in once its side is read, and repeat on the ring inside.
Show the approach
Keep four bounds around the part of the grid not read yet: top, bottom, left and right.
While they still enclose something, read one ring:
- the top row, from
lefttoright, then movetopdown one; - the right column, from
toptobottom, then moverightin one; - if a row is still left, the bottom row from
rightback toleft, then movebottomup one; - if a column is still left, the left column from
bottomback up totop, then moveleftin one.
The two checks matter when the last part is a single row or a single column: without them, it would be read twice.
Time: O(m × n) · Space: O(1) beyond the answer