leetcode/0059_spiral-matrix-ii/python3/solution.py

41 lines
958 B
Python
Raw Normal View History

2022-04-13 01:05:02 +00:00
import math
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
m = [[None] * n for _ in range(n)]
val = 1
for i in range(math.ceil(n / 2)):
# Top
ri, ci = i, i
while ci < n - i:
m[ri][ci] = val
val += 1
ci += 1
ci -= 1
# Right
ri, ci = ri + 1, ci
while ri < n - i:
m[ri][ci] = val
val += 1
ri += 1
ri -= 1
# Bottom
ri, ci = ri, ci - 1
while ci >= i:
m[ri][ci] = val
val += 1
ci -= 1
ci += 1
# Left
ri, ci = ri - 1, ci
while ri > i:
m[ri][ci] = val
val += 1
ri -= 1
return m