54. Spiral Matrix
Your function receives matrix, an m × n grid of integers, and returns a flat list of all m · n values read in clockwise spiral order.
Start at the top-left cell and sweep right across the first row. On hitting the edge, turn and go down the last column, then leftward across the bottom row, then up the first column — and keep coiling inward, never revisiting a cell, until every value has been consumed.
The traversal order is fully determined by the grid's shape, so there is exactly one correct answer for any input.
Example 1:
Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Explanation: Across the top (1 2 3), down the right (6 9), back along the bottom (8 7), up the left (4), and the center (5) last.
Example 2:
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]
Explanation: After the outer ring (1 2 3 4 8 12 11 10 9), only the middle strip 5 6 7 remains, read left to right.
Constraints:
- 1 ≤ m, n ≤ 100
- -10⁹ ≤ matrix[i][j] ≤ 10⁹
Hints:
Think in rings, not cells: peel the outer ring (top row → right column → bottom row → left column), then recurse on the smaller inner rectangle. Four boundary indices — top, bottom, left, right — describe the unpeeled region completely.
The classic bug is double-counting on degenerate inner rectangles (a single row or single column left). Guard the bottom-row and left-column sweeps: only take them while top <= bottom and left <= right still hold after shrinking.
Alternatively, simulate a walker: move in the current direction until the next cell is out of bounds or already visited, then turn clockwise. A visited grid (or overwriting consumed cells with a sentinel) makes the turn test trivial.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Expected output: [1, 2, 3, 6, 9, 8, 7, 4, 5]