Given an m x n
matrix, return all elements of the matrix in spiral order.
m
and columns n
can range from 1 to 10. This ensures that our solution doesn’t need to concern itself with extreme memory management or performance issues.m = 1
and n = 1
.top
, down
, left
, right
) to keep track of the edges of the matrix that are not yet traversed.right
, down
, left
, up
) using an index.def spiralOrder(matrix):
if not matrix:
return []
# Initialize boundary pointers
top, down = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
result = []
direction = 0 # 0 -> right, 1 -> down, 2 -> left, 3 -> up
while top <= down and left <= right:
if direction == 0: # Move right
for col in range(left, right + 1):
result.append(matrix[top][col])
top += 1
elif direction == 1: # Move down
for row in range(top, down + 1):
result.append(matrix[row][right])
right -= 1
elif direction == 2: # Move left
for col in range(right, left - 1, -1):
result.append(matrix[down][col])
down -= 1
elif direction == 3: # Move up
for row in range(down, top - 1, -1):
result.append(matrix[row][left])
left -= 1
# Update direction for next iteration
direction = (direction + 1) % 4
return result
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?