Skip to content

Algorithms

Spiral Matrix Traversal

O(rows · columns) time — every cell is visited exactly once · O(1) extra space, besides the output list.

The idea, in plain English

Imagine peeling a rectangular sticker off a grid from the outside in. Read across the top edge, down the right edge, back across the bottom edge, and up the left edge. Then shrink the rectangle by one layer and repeat. That is a spiral traversal — visiting every item in a grid by walking its shrinking outer ring, over and over, until nothing is left.

How it works

  1. 1Track four boundaries: top, bottom, left, and right. These are the edges of the rectangle you have not visited yet.
  2. 2Walk across the top row from left to right, down the right column from top to bottom, across the bottom row from right to left, and up the left column from bottom to top. Shrink each boundary inward right after you walk it.
  3. 3Before each of the last two walks, check that the boundaries have not crossed yet, since the rectangle might have shrunk to a single row or column. Repeat the whole ring-walk until top passes bottom or left passes right.

When you'd use it

Use it to read or process a 2D grid in a specific visual order — image processing that scans outside-in, generating spiral-numbered puzzles, or any problem that asks for the elements of a grid in spiral order.

Common beginner mistakes

  • Forgetting the 'boundaries have not crossed' checks before the bottom-row and left-column walks. Without them, a single row or column gets walked twice, and cells get counted twice.
  • Shrinking a boundary at the wrong time, before you finish that edge's walk instead of right after. That skips cells or reads the wrong row or column on the next leg.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Spiral order: 1 2 3 4 8 12 11 10 9 5 6 7

See it in motion

Watch it spiralSpiral traversal4×3O(rows · columns) time — every cell is visited exactly once · O(1) extra space, besides the output list.
123456789101112
Spiral order
—

Four boundaries frame the unvisited rectangle. Walk its outer ring, then shrink inward.

0/12
Visited
—
Leg
0/12
Step
0.0s
Time
Current cellVisited ringOutput orderUnvisited

Not sure this is the right topic? See the learning paths → or where this leads →