- JY:矩阵的螺旋遍历
- 相似题:0054_Spiral-Matrix【M】
- 参考:0059_Spiral-Matrix-ii【M】
1、基于 4 个边界指针
- 参考 0054_Spiral-Matrix【M】中的解法 2
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
- 完全参照 0054_Spiral-Matrix【M】的解法 2
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]]
"""
标签:0059,right,bottom,top,Spiral,ii,range,num,left
From: https://blog.csdn.net/m0_66491750/article/details/140633584