给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
# (1)递减
# result=list( range(6,0,-1))#取头不取尾
# print(result)
# 打印结果:
# [6,5,4,3,2,1]
nums = [[0] * n for _ in range(n)]#⭐这一句是抄答案的
startx = 0
starty = 0
offset = 1
count = 1
for circle in range(int(n/2)):
i = startx
j = starty
for j in range(startx, n - offset, 1):
# 注意不要写成range(n - offset),这样每次循环初始都从0下标开始,就不对了
nums[i][j] = count
count = count + 1
j = j + 1
for i in range(starty, n - offset, 1):
nums[i][j] = count
count = count + 1
i = i + 1
for j in range(n - offset, starty, -1):
nums[i][j] = count
count = count + 1
j = j - 1
for i in range(n - offset, startx, -1):
nums[i][j] = count
count = count + 1
i = i - 1
startx = startx + 1
starty = starty + 1
offset = offset + 1
if n%2 == 1:
nums[startx][starty] = count
return nums