Spiral Matrix
Part of Practice: Matrix Choreography
Given an m x n grid of numbers, return all of its values in clockwise spiral order: across the top row left to right, down the right column, backwards along the bottom row, up the left column, then repeat one ring further in until every cell has been visited once.
Constraints that matter: the grid can be a single row, a single column, or non-square — the tricky part is not walking any cell twice when the remaining region collapses to a line.
Examples
- Input:
- matrix = [[1,2,3],[4,5,6],[7,8,9]]
- Output:
- [1,2,3,6,9,8,7,4,5]
Outer ring clockwise: 1,2,3 then 6,9 then 8,7 then 4. The single remaining center cell 5 comes last.
- Input:
- matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
- Output:
- [1,2,3,4,8,12,11,10,9,5,6,7]
After the outer ring, the middle row remnant [6,7] is traversed left to right.
Hints
One at a time — struggle first, peek second.
Your thinking space — verify on LeetCode, then mark it.