41 lines
958 B
Python
41 lines
958 B
Python
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
|