class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if len(matrix) == 0:
return []
n, m = len(matrix), len(matrix[0])
num_total, res = n * m, []
left, right, top, bottom = 0, m - 1, 0, n - 1
while len(res) < num_total:
if len(res) < num_total:
for j in range(left, right + 1):
res.append(matrix[top][j])
top += 1
if len(res) < num_total:
for i in range(top, bottom + 1):
res.append(matrix[i][right])
right -= 1
if len(res) < num_total:
for j in range(right, left - 1, -1):
res.append(matrix[bottom][j])
bottom -= 1
if len(res) < num_total:
for i in range(bottom, top - 1, -1):
res.append(matrix[i][left])
left += 1
return res