Explain spiral matrix traversal.
01
01
Understand the problem
matrixsimulation
02
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Stuck? AI Nudge Available
Get a conceptual hint to guide your logic without spoiling the final implementation.
03
03
Study the solution
The solution is waiting
Give it an honest attempt first — then compare your thinking with the full walkthrough.
04
04
Read the code
Four-boundary spiral
Run Playgrounddef spiral_order(matrix):
if not matrix: return []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
res = []
while top <= bottom and left <= right:
for c in range(left, right + 1): res.append(matrix[top][c])
top += 1
for r in range(top, bottom + 1): res.append(matrix[r][right])
right -= 1
if top <= bottom:
for c in range(right, left - 1, -1): res.append(matrix[bottom][c])
bottom -= 1
if left <= right:
for r in range(bottom, top - 1, -1): res.append(matrix[r][left])
left += 1
return res
# --- demo ---
print(spiral_order([[1, 2, 3], [8, 9, 4], [7, 6, 5]]))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]05
05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.