和遍历一样设置四个边界按顺序一层层的生成
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
matrix = [[0]*n for i in range(n)]
count = 1
l,r = 0,len(matrix[0])-1
t,b = 0,len(matrix)-1
while count <= n*n:
for i in range(l,r+1):
matrix[t][i] = count
count += 1
t += 1
for i in range(t,b+1):
matrix[i][r] = count
count += 1
r -= 1
for i in range(r,l-1,-1):
matrix[b][i] = count
count += 1
b -= 1
for i in range(b,t-1,-1):
matrix[i][l] = count
count += 1
l += 1
return matrix