# O(m*n) Python solution using 4 directions

• ``````class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
result = []
########  corner cases
if not matrix:
return result
length = len(matrix[0]) * len(matrix) # calculate length
if length == 1:
result.append(matrix[0][0])
return result
########
direction = 0       # 0=go right 1=go down 2=go left 3=go up
row, col, step = 0, 0, 0
while len(result) < length:
if direction == 0:
while col <= len(matrix[0])-1-step:
result.append(matrix[row][col])
col += 1
col -= 1
direction += 1
elif direction == 1:
row += 1
while row <= len(matrix)-1-step:
result.append(matrix[row][col])
row += 1
row -= 1
direction += 1
elif direction == 2:
col -= 1
while col >= 0 + step:
result.append(matrix[row][col])
col -= 1
col += 1
direction += 1
elif direction == 3:
row -= 1
while row > 0 + step:
result.append(matrix[row][col])
row -= 1
direction = 0
step += 1
row, col = step, step
return result

``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.