DSA Tracker

Visualize

Spiral Matrix

Four shrinking boundaries

time O(rows * cols)space O(1) extra

A spiral is just four straight walks repeated: right along the top row, down the right column, left along the bottom row, up the left column — then shrink whichever boundary you just finished and repeat on the smaller rectangle inside. Track top/bottom/left/right boundaries; the walk stops once they cross.

Details

Animated on: matrix = [[1,2,3],[4,5,6],[7,8,9]] — return all elements in spiral order (shown flattened row-major, index = row*3+col).

Problem:Spiral MatrixMedium

Four shrinking boundaries

step 1 / 10

1
[0]
2
[1]
3
[2]
4
[3]
5
[4]
6
[5]
7
[6]
8
[7]
9
[8]

Start at top-left, heading right. Visit 1 (idx0).

  • cur=0· arr[0] = 1
Pseudocode
1FUNCTION spiralOrder(matrix):
2 top = 0, bottom = rows - 1, left = 0, right = cols - 1
3 WHILE top <= bottom and left <= right:
4 walk right along row top, then move top one row down
5 walk down along column right, then move right one column left
6 walk left along row bottom, then move bottom one row up
7 walk up along column left, then move left one column right
8 RETURN the collected values

← / → step · space play · Home restart

Every step in words

Show all 10 steps
  1. Start at top-left, heading right. Visit 1 (idx0).
  2. Continue right along the top row: visit 2 (idx1).
  3. Top row done: visit 3 (idx2). Top boundary shrinks down — turn to walk down the right column.
  4. Walk down the right column: visit 6 (idx5).
  5. Continue down: visit 9 (idx8). Right column done — right boundary shrinks left, turn to walk left along the bottom row.
  6. Walk left along the bottom row: visit 8 (idx7).
  7. Continue left: visit 7 (idx6). Bottom row done — bottom boundary shrinks up, turn to walk up the left column.
  8. Walk up the left column: visit 4 (idx3). Left boundary shrinks right.
  9. Boundaries have closed in to a single cell: visit the center, 5 (idx4).
  10. Spiral traversal complete: [1,2,3,6,9,8,7,4,5].

Now solve it yourself

Watching is the first half. The second is writing it without the animation.