class Solution:
def spiralOrder(self, matrix: list[list[int]]) -> list[int]:
if not matrix or not matrix[0]:
return []
M, N = len(matrix), len(matrix[0])
result = []
left, right, top, bottom = 0, N - 1, 0, M - 1
while left <= right and top <= bottom:
for column in range(left, right + 1):
result.append(matrix[top][column])
for row in range(top + 1, bottom + 1):
result.append(matrix[row][right])
if left < right and top < bottom:
for column in range(right - 1, left, -1):
result.append(matrix[bottom][column])
for row in range(bottom, top, -1):
result.append(matrix[row][left])
left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
return result