Visualize

Pattern visualizer

Spiral Matrix

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. 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)..

Four shrinking boundaries

time O(rows * cols)space O(1) extrastep 1 / 10
1
[0]
2
[1]
3
[2]
4
[3]
5
[4]
6
[5]
7
[6]
8
[7]
9
[8]
line 4

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

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

Where to practice Matrix