Skip to main content

54. Spiral Matrix

https://leetcode.com/problems/spiral-matrix/

Python

  • Time: O(m*n)
  • Space: O(m*n) # the visited hashmap
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m = len(matrix)
n = len(matrix[0])

limit = m*n
visited = set()
result = []

direction = 'right'
x, y = 0, 0
while len(result) < limit:
result.append(matrix[y][x])
visited.add((x, y))

if direction == 'right':
if x+1 < n and (x+1, y) not in visited:
x += 1
else:
direction = 'down'
y += 1
elif direction == 'down':
if y+1 < m and (x, y+1) not in visited:
y += 1
else:
direction = 'left'
x -= 1
elif direction == 'left':
if x-1 >= 0 and (x-1, y) not in visited:
x -= 1
else:
direction = 'up'
y -= 1
else:
if y-1 >= 0 and (x, y-1) not in visited:
y -= 1
else:
direction = 'right'
x += 1

return result