1
class Solution:
2
def generateMatrix(self, n: int) -> List[List[int]]:
3
if not n:
4
return []
5
matrix = [[0 for _ in range(n)] for _ in range(n)]
6
left, right, top, bottom, num = 0, n - 1, 0, n - 1, 1
7
while left <= right and top <= bottom:
8
for i in range(left, right + 1):
9
matrix[top][i] = num
10
num += 1
11
top += 1
12
for i in range(top, bottom + 1):
13
matrix[i][right] = num
14
num += 1
15
right -= 1
16
if top <= bottom:
17
for i in range(right, left - 1, -1):
18
matrix[bottom][i] = num
19
num += 1
20
bottom -= 1
21
if left <= right:
22
for i in range(bottom, top - 1, -1):
23
matrix[i][left] = num
24
num += 1
25
left += 1
26
return matrix

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0