We maintain four boundaries: top, bottom, left, and right. While the boundaries haven't crossed each other, we traverse the matrix in a clockwise spiral.
top = 0,bottom = m - 1,left = 0,right = n - 1.- While
top <= bottomandleft <= right:- Traverse from
lefttorightalongtop. Incrementtop. - Traverse from
toptobottomalongright. Decrementright. - If
top <= bottom:- Traverse from
righttoleftalongbottom. Decrementbottom.
- Traverse from
- If
left <= right:- Traverse from
bottomtotopalongleft. Incrementleft.
- Traverse from
- Traverse from
- Return the result list.
- Time Complexity: O(M * N).
- Space Complexity: O(1) (ignoring output array).
def spiral_order(matrix):
if not matrix: return []
m, n = len(matrix), len(matrix[0])
top, bottom, left, right = 0, m - 1, 0, n - 1
res = []
while len(res) < m * n:
# 1. Left to Right
for j in range(left, right + 1):
res.append(matrix[top][j])
top += 1
# 2. Top to Bottom
if len(res) < m * n:
for i in range(top, bottom + 1):
res.append(matrix[i][right])
right -= 1
# 3. Right to Left
if len(res) < m * n:
for j in range(right, left - 1, -1):
res.append(matrix[bottom][j])
bottom -= 1
# 4. Bottom to Top
if len(res) < m * n:
for i in range(bottom, top - 1, -1):
res.append(matrix[i][left])
left += 1
return res