Algorithms · Visualized
Matrix: Spiral Matrix
Matrix & 2D
Rotations, traversals, and grid searches on 2D arrays.
Visits every element of a matrix in a spiral order: right across the top row, down the right column, left across the bottom row, up the left column, then shrinking the boundary inward and repeating until every element has been visited. Time: O(rows × cols) average, O(rows × cols) — visits every cell exactly once worst; space: O(1) extra beyond the output list.
Big-O: Classic O(m·n) sweeps and in-place tricks.
Spiral Traversal
Matrix / 2D ArrayVisits every element of a matrix in a spiral order: right across the top row, down the right column, left across the bottom row, up the left column, then shrinking the boundary inward and repeating until every element has been visited.
How Spiral Matrix Works
- Track four boundaries: top, bottom, left, and right, initially set to the matrix's outer edges.
- Traverse from left to right along the 'top' row, then move the 'top' boundary down by one.
- Traverse from top to bottom along the 'right' column, then move the 'right' boundary left by one.
- If the top boundary hasn't crossed the bottom, traverse right to left along the 'bottom' row, then move the 'bottom' boundary up by one; if the left boundary hasn't crossed the right, traverse bottom to top along the 'left' column, then move the 'left' boundary right by one.
- Repeat this cycle, shrinking the boundaries each time, until top exceeds bottom or left exceeds right.
Spiral Matrix Worked Example
Input: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Top row left-to-right: 1,2,3. Right column top-to-bottom: 6,9. Bottom row right-to-left: 8,7. Left column bottom-to-top (within shrunk bounds): 4. Center remains: 5. Full spiral order: [1,2,3,6,9,8,7,4,5].
def spiral_matrix(m):
out = []
top, bot = 0, len(m) - 1
le, ri = 0, len(m[0]) - 1
while top <= bot and le <= ri:
out += m[top][le:ri + 1]
top += 1
out += [m[i][ri] for i in range(top, bot + 1)]
ri -= 1
if top <= bot:
out += m[bot][le:ri + 1][::-1]
bot -= 1
if le <= ri:
out += [m[i][le] for i in range(bot, top - 1, -1)]
le += 1
return outBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Spiral Matrix Time & Space Complexity
When to Use Spiral Matrix
- Printing/scanning data in spiral order for display effects, image filters, or puzzle generation.
- A common pattern for testing careful boundary/index management in grid traversal.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.