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 Array

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.

How Spiral Matrix Works

  1. Track four boundaries: top, bottom, left, and right, initially set to the matrix's outer edges.
  2. Traverse from left to right along the 'top' row, then move the 'top' boundary down by one.
  3. Traverse from top to bottom along the 'right' column, then move the 'right' boundary left by one.
  4. 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.
  5. 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].

Matrix: Spiral MatrixO(m·n)
Read a matrix in clockwise spiral order.
1
2
3
4
5
6
7
8
9
Step 1 / 11
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Spiral Matrix: read the elements in a clockwise spiral from the outside in.
Python · Matrix Algorithms in Code
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 out

Behind 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

BestO(rows × cols)
AverageO(rows × cols)
WorstO(rows × cols) — visits every cell exactly once
SpaceO(1) extra beyond the output list

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.