class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
m = [[0] * n for _ in range(n)]
row, col = 0, 0
num, direc = 1, 0
# 定义行进方向0,1,2,3分别代表右下左上,主要还是边界的判断
while num <= n ** 2:
if m[row][col] == 0:
m[row][col] = num
num += 1
if direc == 0:
if col < n-1 and m[row][col+1] == 0:
col += 1
else:
direc += 1
elif direc == 1:
if row < n-1 and m[row+1][col] == 0:
row += 1
else:
direc += 1
elif direc == 2:
if col > 0 and m[row][col-1] == 0:
col -= 1
else:
direc += 1
else:
if row > 0 and m[row-1][col] == 0:
row -= 1
else:
direc += 1
# 方向需要轮回
direc %= 4
return m
LeetCode 59 旋转矩阵II
最新推荐文章于 2025-12-10 14:25:37 发布
本文介绍了一种使用动态规划方法实现的生成矩阵问题的解决方案,通过递推和边界条件控制,生成一个n阶的矩阵,遵循特定的填充规律。
1982

被折叠的 条评论
为什么被折叠?



