Skip to main content

59. Spiral Matrix II

Python

class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
matrix = [[None]*n for i in range(n)]

direction = 'right'
x, y = 0, 0

for i in range(1, n**2+1):
matrix[y][x] = i

if direction == 'right':
if x+1 < n and matrix[y][x+1] is None:
x += 1
else:
direction = 'down'
y += 1
elif direction == 'down':
if y+1 < n and matrix[y+1][x] is None:
y += 1
else:
direction = 'left'
x -= 1
elif direction == 'left':
if x-1 >= 0 and matrix[y][x-1] is None:
x -= 1
else:
direction = 'up'
y -= 1
else:
# up
if y-1 >= 0 and matrix[y-1][x] is None:
y -= 1
else:
direction = 'right'
x += 1

return matrix