Python 实现矩阵顺时针螺旋遍历
下面是使用 Python 编写的按顺时针螺旋顺序遍历矩阵的代码:
def spiralOrder(matrix):
if not matrix:
return []
rows, cols = len(matrix), len(matrix[0])
left, right, top, bottom = 0, cols - 1, 0, rows - 1
result = []
while left <= right and top <= bottom:
# 从左向右遍历
for col in range(left, right + 1):
result.append(matrix[top][col])
# 从上到下遍历
for row in range(top + 1, bottom + 1):
result.append(matrix[row][right])
# 防止重复遍历同一行或同一列
if left < right and top < bottom:
# 从右到左遍历
for col in range(right - 1, left - 1, -1):
result.append(matrix[bottom][col])
# 从下到上遍历
for row in range(bottom - 1, top, -1):
result.append(matrix[row][left])
# 更新边界
left += 1
right -= 1
top += 1
bottom -= 1
return result
# 获取输入
m = int(input('请输入矩阵的行数 m:'))
n = int(input('请输入矩阵的列数 n:'))
matrix = []
print('请输入矩阵的元素:')
for i in range(m):
row = list(map(int, input().split()))
matrix.append(row)
# 调用函数并输出结果
result = spiralOrder(matrix)
print('按顺时针螺旋顺序遍历矩阵的结果为:', result)
请在运行程序时按照提示输入矩阵的行数 m 和列数 n,并依次输入矩阵的元素。程序将按顺时针螺旋顺序遍历矩阵,并输出结果。
原文地址: https://www.cveoy.top/t/topic/clt5 著作权归作者所有。请勿转载和采集!