101. Spiral Matrix

Medium · Array

Given an m × n matrix, return all elements of the matrix in spiral order (clockwise from outside to inside).

Spiral order means: traverse the top row left-to-right, then the right column top-to-bottom, then the bottom row right-to-left, then the left column bottom-to-top, and repeat for the inner rectangle until all elements are visited.

Examples

Example 1
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Explanation: Start at top-left (1), go right (2,3), down (6,9), left (8,7), up (4), then inward (5).
Example 2
Input: [[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: Outer spiral: 1→2→3→4→8→12→11→10→9→5, then inner row: 6→7.

Constraints