Spiral Matrix
Problem
Given an m x n matrix, return all elements of the matrix in spiral order.
Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Brainstorming
The core idea is to simulate the spiral path. We maintain boundaries (top, bottom, left, right) and shrink them as we traverse each side.
- Initialize boundaries:
top = 0bottom = m - 1left = 0right = n - 1
- Loop while boundaries are valid:
- Move Right: Traverse from
lefttorightalong thetoprow. Then incrementtop. - Move Down: Traverse from
toptobottomalong therightcolumn. Then decrementright. - Move Left (if top <= bottom): Traverse from
righttoleftalong thebottomrow. Then decrementbottom. - Move Up (if left <= right): Traverse from
bottomtotopalong theleftcolumn. Then incrementleft.
- Move Right: Traverse from
Code
def spiralOrder(matrix):
if not matrix:
return []
m, n = len(matrix), len(matrix[0])
top, bottom = 0, m - 1
left, right = 0, n - 1
result = []
while top <= bottom and left <= right:
# Move Right
for i in range(left, right + 1):
result.append(matrix[top][i])
top += 1
# Move Down
for i in range(top, bottom + 1):
result.append(matrix[i][right])
right -= 1
# Move Left
if top <= bottom:
for i in range(right, left - 1, -1):
result.append(matrix[bottom][i])
bottom -= 1
# Move Up
if left <= right:
for i in range(bottom, top - 1, -1):
result.append(matrix[i][left])
left += 1
return result