Imagine you're a treasure hunter exploring a rectangular grid filled with precious gems. Your goal is to collect all the gems by walking in a spiral pattern - starting from the top-left corner, moving right along the top edge, then down the right edge, left along the bottom, up the left edge, and continuing this spiral pattern inward until you've collected every single gem!
Given an m x n matrix, return all elements traversed in clockwise spiral order. You'll start at matrix[0][0] and spiral inward, collecting elements as you go.
Example: For matrix [[1,2,3],[4,5,6],[7,8,9]], the spiral path would be: 1 → 2 → 3 → 6 → 9 → 8 → 7 → 4 → 5, forming a clockwise spiral from outside to inside.
Input & Output
Visualization
Time & Space Complexity
Visit each cell exactly once in the m×n matrix
Only using constant extra space for boundary variables (excluding result array)
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 ≤ m, n ≤ 10
- -100 ≤ matrix[i][j] ≤ 100