class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
left, right, top, bottom = 0, n - 1, 0, n - 1
total = n * n
num = 1
mat = [[0] *n for _ in range(n)]
while num <= total:
# 注意range的左闭右开
for lr in range(left,right + 1): # 从左到右,填充了一行
mat[top][lr] = num # 注意矩阵的索引
num += 1
top += 1 # top是起点,从左到右一轮,上边界缩一行+1
for tb in range(top,bottom + 1): # 从上到下,填充了一列
mat[tb][right] = num # 注意矩阵的索引
num += 1
right -= 1 # right是终点,从上到下一轮右边界缩一列-1
for rl in range(right,left - 1,-1): # 从右到左,填充了一行,逆序
mat[bottom][rl] = num # 注意矩阵的索引
num += 1
bottom -= 1 # bottom是终点,从右到左一轮,下边界缩一行-1
for bt in range(bottom,top - 1,-1):
mat[bt][left] = num
num += 1
left += 1
return mat
力扣59. 螺旋矩阵 II
第一次做这种,稍微有点吃力,主要是针对矩阵索引不熟悉的话比较难,还有转角的处理。细节都打了注释。
参考的力扣解析,卡哥的没听太懂。