← Back to DSA Animator
Spiral Matrix LC #54 Medium 4-Boundary Peel
Problem

Given an m × n matrix, return all elements of the matrix in spiral order (clockwise from the top-left).

Example 1
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Explanation: Traverse outer ring clockwise then inner ring.
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: 3×4 spiral — two passes, first outer ring then inner row.
Example 3
Input: matrix = [[1]]
Output: [1]
Constraints: 1 ≤ m, n ≤ 10  |  −100 ≤ matrix[i][j] ≤ 100
Try Examples
Custom:
Approach
Four Boundaries: top, bottom, left, right — shrink after each directional pass
Traverse right→down→left→up, shrink boundary, repeat until all visited
Matrix — Spiral Traversal
Direction:
→ Right
top
bottom
left
right
Result (spiral order)
( empty )
Boundary State
Direction
top
bottom
left
right
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Init four boundaries: top=0, bottom=m-1, left=0, right=n-1
2
→ Traverse top row left to right; then top++
3
↓ Traverse right column top to bottom; then right--
4
← Traverse bottom row right to left (if top≤bottom); then bottom--
5
↑ Traverse left column bottom to top (if left≤right); then left++
6
Repeat while top≤bottom && left≤right
Time
O(m×n)
Space
O(1)
Why 4-Boundary Peel Works

Instead of tracking visited cells, we use four integer boundaries that shrink inward after each directional pass. This guarantees every cell is visited exactly once in spiral clockwise order, with O(1) extra space.

The if (top<=bottom) and if (left<=right) guards prevent double-counting the last row or column when the spiral collapses to a single row/column.