![](https://img-blog.csdnimg.cn/img_convert/58381f6e4562849fc1f8c93ad7a8510e.png)
![](https://img-blog.csdnimg.cn/img_convert/c33ab0e6eb63d6bf4628d3a2921d8902.png)
![](https://img-blog.csdnimg.cn/img_convert/c6643852ae4cc978acbb0750862d1a48.png)
1、基于 4 个边界指针
class Solution:
def generateMatrix(self, n: int) -> [[int]]:
left, right, top, bottom = 0, n-1, 0, n-1
# jy: 初始化矩阵框架, 初始值均为 0
matrix = [[0 for _ in range(n)] for _ in range(n)]
# jy: 计算待填充的数值范围 [num, max_num]
num, max_num = 1, n * n
# jy: 数值范围确定, 不会存在边界指针越界问题
while num <= max_num:
for i in range(left, right + 1):
matrix[top][i] = num
num += 1
top += 1
for i in range(top, bottom + 1):
matrix[i][right] = num
num += 1
right -= 1
for i in range(right, left - 1, -1):
matrix[bottom][i] = num
num += 1
bottom -= 1
for i in range(bottom, top - 1, -1):
matrix[i][left] = num
num += 1
left += 1
return matrix
n = 1
res = Solution().generateMatrix(n)
print(res)
"""
[[1]]
"""
2、改写解法 1
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
left, right, top, bottom = 0, n-1, 0, n-1
matrix = [[0 for _ in range(n)] for _ in range(n)]
num = 1
# jy: 数值范围只确定了初始数值, 结束数值未定, 因此填充时可能存
# 在边界指针越界问题
while True:
for i in range(left, right + 1):
matrix[top][i] = num
num += 1
top += 1
if top > bottom:
break
for i in range(top, bottom + 1):
matrix[i][right] = num
num += 1
right -= 1
if right < left:
break
for i in range(right, left - 1, -1):
matrix[bottom][i] = num
num += 1
bottom -= 1
if bottom < top:
break
for i in range(bottom, top - 1, -1):
matrix[i][left] = num
num += 1
left += 1
if left > right:
break
return matrix
n = 3
res = Solution().generateMatrix(n)
print(res)
"""
[[1, 2, 3],
[8, 9, 4],
[7, 6, 5]]
"""