Spiral Matrix
Four shrinking boundaries
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
Start at top-left, heading right. Visit 1 (idx0).
- cur=0· arr[0] = 1
1FUNCTION spiralOrder(matrix):2 top = 0, bottom = rows - 1, left = 0, right = cols - 13 WHILE top <= bottom and left <= right:4 walk right along row top, then move top one row down5 walk down along column right, then move right one column left6 walk left along row bottom, then move bottom one row up7 walk up along column left, then move left one column right8 RETURN the collected values
← / → step · space play · Home restart
Every step in words
Show all 10 steps
- Start at top-left, heading right. Visit 1 (idx0).
- Continue right along the top row: visit 2 (idx1).
- Top row done: visit 3 (idx2). Top boundary shrinks down — turn to walk down the right column.
- Walk down the right column: visit 6 (idx5).
- Continue down: visit 9 (idx8). Right column done — right boundary shrinks left, turn to walk left along the bottom row.
- Walk left along the bottom row: visit 8 (idx7).
- Continue left: visit 7 (idx6). Bottom row done — bottom boundary shrinks up, turn to walk up the left column.
- Walk up the left column: visit 4 (idx3). Left boundary shrinks right.
- Boundaries have closed in to a single cell: visit the center, 5 (idx4).
- 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.