1def spiralOrder(matrix):
2 result = []
3 top, bottom = 0, len(matrix) - 1
4 left, right = 0, len(matrix[0]) - 1
5
6 while top <= bottom and left <= right:
7 # Traverse right
8 for col in range(left, right + 1):
9 result.append(matrix[top][col])
10 top += 1
11
12 # Traverse down
13 for row in range(top, bottom + 1):
14 result.append(matrix[row][right])
15 right -= 1
16
17 # Traverse left
18 if top <= bottom:
19 for col in range(right, left - 1, -1):
20 result.append(matrix[bottom][col])
21 bottom -= 1
22
23 # Traverse up
24 if left <= right:
25 for row in range(bottom, top - 1, -1):
26 result.append(matrix[row][left])
27 left += 1
28
29 return result