List every matrix cell in clockwise spiral order, beginning at the top-left corner.
Problem
Input. A rectangular integer matrix, possibly with an empty dimension.
Output. Return a flat list of all cell values in clockwise spiral order.
Rules. Begin at the top-left and initially move right, following successive outer boundaries inward.
Visit every cell exactly once, including repeated or negative values.
Leave the matrix unchanged. Empty dimensions return []; ragged rows are outside the contract.
Example. [[1, 2, 3], [4, 5, 6], [7, 8, 9]] returns [1, 2, 3, 6, 9, 8, 7, 4, 5].
A one-row matrix [[1, 2, 3]] returns [1, 2, 3] without repeated cells.
Picture
For [[1,2,3], [4,5,6]], read top 1,2,3, right 6, then bottom 5,4.
The unread bounds have crossed, so stop.
Problem trace
Separate one-row remainder: no second sweep after the rectangle disappears
Reference drawing
Problem trace
Recheck the remaining boundaries before traversing another edge
Execution trace
- read cursor
- (0, 0)
- boundaries
- top=0 bottom=2 left=0 right=3
- answer
- []
- read cursor
- (0, 0)→(0, 3)
- direction
- not shown→(0,0) -> (0,3)
- boundaries
- top=0 bottom=2 left=0 right=3→top=1 bottom=2 left=0 right=3
- read cursor
- (0, 3)→(2, 3)
- direction
- (0,0) -> (0,3)→(1,3) -> (2,3)
- boundaries
- top=1 bottom=2 left=0 right=3→top=1 bottom=2 left=0 right=2
- read cursor
- (2, 3)→(2, 0)
- direction
- (1,3) -> (2,3)→(2,2) -> (2,0)
- boundaries
- top=1 bottom=2 left=0 right=2→top=1 bottom=1 left=0 right=2
- read cursor
- (2, 0)→(1, 0)
- direction
- (2,2) -> (2,0)→(1,0) -> (1,0)
- boundaries
- top=1 bottom=1 left=0 right=2→top=1 bottom=1 left=1 right=2
- read cursor
- (1, 0)→(1, 2)
- direction
- (1,0) -> (1,0)→(1,1) -> (1,2)
- boundaries
- top=1 bottom=1 left=1 right=2→top=2 bottom=1 left=1 right=2
- read cursor
- (1, 2)→(1, 1)
- boundaries
- top=2 bottom=1 left=1 right=2→top=2 bottom=1 left=2 right=1
- guard
- not shown→top>bottom; no row remains
- Recognize it
- Use boundary peeling when a rectangular grid must be traversed layer by layer around its perimeter in directional order.
- Keep true
- At each while-loop entry, every cell outside top..bottom and left..right has been emitted exactly once, and every unvisited cell lies inside that closed rectangle.
- Reuse it
- For perimeter traversals, represent remaining work as explicit inclusive bounds, consume one edge, shrink it immediately, and guard later edges because earlier moves may collapse the region.
Each completed side is removed from the unread rectangle before another side is visited. The bottom and left guards prevent revisiting cells after a thin rectangle disappears.
Code
def spiral_order(matrix: list[list[int]]) -> list[int]:
if not matrix or not matrix[0]:
return []
answer = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
answer.extend(matrix[top][left : right + 1])
top += 1
for row in range(top, bottom + 1):
answer.append(matrix[row][right])
right -= 1
if top <= bottom:
answer.extend(reversed(matrix[bottom][left : right + 1]))
bottom -= 1
if left <= right:
for row in range(bottom, top - 1, -1):
answer.append(matrix[row][left])
left += 1
return answer
Cost: cell visits and output storage, plus temporary slicing space. The four bounds themselves use constant state.
Change the Requirement
Stream Coordinates Without Slices
New task: Yield positions lazily using constant auxiliary state.
Picture and change: Keep the rectangle but replace copied rows with indexed visits.
Code: Nonnegative integer dimensions are required.
def spiral_positions(rows: int, cols: int):
if rows < 0 or cols < 0:
raise ValueError("dimensions must be nonnegative")
top, bottom, left, right = 0, rows - 1, 0, cols - 1
while top <= bottom and left <= right:
for col in range(left, right + 1):
yield top, col
top += 1
for row in range(top, bottom + 1):
yield row, right
right -= 1
if top <= bottom:
for col in range(right, left - 1, -1):
yield bottom, col
bottom -= 1
if left <= right:
for row in range(bottom, top - 1, -1):
yield row, left
left += 1
Check: list(spiral_positions(1, 3)) returns [(0,0), (0,1), (0,2)] once each.
Use when: Consumers need positions incrementally. Exhaustion costs time; storing yielded positions is the consumer’s choice.
Reverse Traversal Orientation
New task: Visit counterclockwise, still starting at top-left.
Picture and change: Transposition exchanges horizontal and vertical movements, reversing orientation.
Code: Reuse the complete reference on a transposed copy.
def spiral_counterclockwise(matrix: list[list[int]]) -> list[int]:
if not matrix or not matrix[0]:
return []
transposed = [
[matrix[row][col] for row in range(len(matrix))]
for col in range(len(matrix[0]))
]
return spiral_order(transposed)
Check: [[1,2,3], [4,5,6]] produces [1,4,5,6,3,2].
Use when: The initial direction is down rather than right. The copy adds workspace.
Reconstruct
What happens without the bottom-side guard?
Reasoned answer
For [[1,2,3]], consuming the top row leaves top > bottom.
Reading the bottom anyway would append previously visited cells.
The guard checks that a side still belongs to the unread rectangle.