Approach
Maintain four boundaries (top, bottom, left, right) and traverse the matrix in layers: top row, right column, bottom row, left column, shrinking boundaries after each pass. Stop when the boundaries cross.
Why It Works
Each boundary traversal visits a unique outer layer of the matrix. Shrinking the boundaries ensures each element is visited exactly once in spiral order.
Complexity
- Time:
O(m * n)
- Space:
O(1)
Reference Implementation (Python)
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix or not matrix[0]:
return []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
result = []
while top <= bottom and left <= right:
for c in range(left, right + 1):
result.append(matrix[top][c])
top += 1
for r in range(top, bottom + 1):
result.append(matrix[r][right])
right -= 1
if top <= bottom:
for c in range(right, left - 1, -1):
result.append(matrix[bottom][c])
bottom -= 1
if left <= right:
for r in range(bottom, top - 1, -1):
result.append(matrix[r][left])
left += 1
return result