python 代码求助 按照顺时针螺旋顺序输出矩阵中的所有元素
本帖最后由 成成是我 于 2022-12-12 08:36 编辑请按照顺时针螺旋顺序输出矩阵中的所有元素
>>> matrix = [,
... ,
... ]
那么将输出:
代码清单:
matrix = [,
,
]
rows = len(matrix)
cols = len(matrix)
left = 0
right = cols - 1
top = 0
bottom = rows - 1
result = []
while left <= right and top <= bottom:
# 从左往右遍历
for col in range(left, right + 1):
result.append(matrix)
# 从上往下遍历
for row in range(top + 1, bottom + 1):
result.append(matrix)
if left < right and top < bottom:
# 从右往左遍历
for col in range(right - 1, left, -1):
result.append(matrix)
# 从下往上遍历
for row in range(bottom, top, -1):
result.append(matrix)
left = left + 1
right = right - 1
top = top + 1
bottom = bottom - 1
print(result)
请大佬解释下红字部分:
1.right 和botton 初始值为什么要-1?
2.请解释下循环范围
感谢感谢!{:5_99:} 1、right表示最右侧一列(序号从left=0开始),bottom 表示最下面一行(序号从top=0开始)
2、每一个for循环都是先确定行或者列号,然后遍历剩下的数for col in range(left, right + 1):
result.append(matrix) #行是确定的,即为top
# 从上往下遍历
for row in range(top + 1, bottom + 1):
result.append(matrix) #列是确定的,即为right
if left < right and top < bottom:
# 从右往左遍历
for col in range(right - 1, left, -1):
result.append(matrix)#行是确定的,即为botton
# 从下往上遍历
for row in range(bottom, top, -1):
result.append(matrix) #列是确定的,即为left
# 从左往右遍历,首先是第一行既top=0保持不变,matrix=,col从0到right值就可以把matrix的所有值取出来,既1, 2, 3, 4
for col in range(left, right + 1):
result.append(matrix) #行是确定的,即为top
# 从上往下遍历,这个时候从最右侧这列开始(最右侧这一列的第二个元素开始,因为这一列第一个元素既4已经在上面被取出来了),这一列的元素来着不同的matrix的最后一个元素。既 8, 12
for row in range(top + 1, bottom + 1):
result.append(matrix) #列是确定的,即为right
if left < right and top < bottom:
# 从右往左遍历,这个时候从最下面一行开始(最下面一行的倒数第二个元素开始,因为这一行的最后第一个元素既12已经在上面被取出来了),既11, 10, 9。
for col in range(right - 1, left, -1):
result.append(matrix)#行是确定的,即为botton
# 从下往上遍历
for row in range(bottom, top, -1):
result.append(matrix) #列是确定的,即为left lxping 发表于 2022-12-9 17:20
嗯嗯,明白了,要把之前取出的数摘出去,谢谢啦{:5_109:}
页:
[1]