题目
给定一个正整数 n,生成一个包含 1 到 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例1
输入: 3输出:[[ 1, 2, 3 ],[ 8, 9, 4 ],[ 7, 6, 5 ]]
实现
思路1
该题的思路其实与Leetcode第54题“螺旋矩阵”一样,只需要按模拟螺旋顺序往矩阵里填充数字即可。
语雀内容
与第54题一样,循环遍历一个边后,另一个边的遍历个数将减小1.
之前我写的代码有点长,因为遍历matrix位置时只用了x,y两个变量。这里使用top, right, bottom, left四个变量来表示matrix中的元素位置,代码看起来会更加精炼。
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
left, right, top, bottom = 0, n-1, 0, n-1
total = n*n
matrix = [[0 for _ in range(n)] for _ in range(n)]
count = 1
# 当所有数字全部遍历后,终止循环
while count<=total:
# 遍历上边
for y in range(left, right+1):
matrix[top][y] = count
count += 1
top += 1
# 遍历右边
for x in range(top, bottom+1):
matrix[x][right] = count
count += 1
right -= 1
# 遍历下边
for y in range(right, left-1, -1):
matrix[bottom][y] = count
count += 1
bottom -= 1
# 遍历左边
for x in range(bottom, top-1, -1):
matrix[x][left] = count
count += 1
left += 1
return matrix
时间复杂度:,因为一共要遍历n*n个元素
