Matrix Spiral Traversal - Problem
Given an m x n matrix, return all elements of the matrix in spiral order (clockwise from outside to inside).
The spiral traversal should start from the top-left corner and move in the following pattern:
- Move right across the top row
- Move down the right column
- Move left across the bottom row
- Move up the left column
- Repeat for inner layers until all elements are visited
Return the elements as a list/array in the order they were visited.
Input & Output
Example 1 — Basic 3x3 Matrix
$
Input:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
›
Output:
[1,2,3,6,9,8,7,4,5]
💡 Note:
Start top-left, go right (1→2→3), down (6→9), left (8→7), up (4), then center (5)
Example 2 — Single Row Matrix
$
Input:
matrix = [[1,2,3,4]]
›
Output:
[1,2,3,4]
💡 Note:
Single row: traverse left to right, no spiral needed
Example 3 — Single Column Matrix
$
Input:
matrix = [[1],[2],[3]]
›
Output:
[1,2,3]
💡 Note:
Single column: traverse top to bottom, no horizontal movement
Constraints
- 1 ≤ m, n ≤ 10
- -100 ≤ matrix[i][j] ≤ 100
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code