输入一个矩阵顺时针逆时针螺旋输出矩阵代码
时间: 2024-11-11 13:13:36 浏览: 14
C++实现:螺旋矩阵的实例代码
5星 · 资源好评率100%
顺时针或逆时针螺旋打印矩阵是一种常见的编程挑战,通常涉及两个嵌套循环以及一些条件判断。这里是一个基本的Python代码示例,用于将二维矩阵按照顺时针螺旋方式进行输出:
```python
def spiral_order(matrix):
if not matrix:
return []
rows = len(matrix)
cols = len(matrix[0])
top, bottom, left, right = 0, rows - 1, 0, cols - 1
direction = 0 # 0: right -> down -> left -> up
result = []
while top <= bottom and left <= right:
# Move right
for _ in range(left, right + 1):
result.append(matrix[top][_])
top += 1
# Move down
if direction != 2:
for _ in range(top, bottom + 1):
result.append(matrix[_][right])
right -= 1
# Move left
if direction != 1:
for _ in range(right, left - 1, -1):
result.append(matrix[bottom][_])
bottom -= 1
# Move up
if direction != 0:
for _ in range(bottom, top - 1, -1):
result.append(matrix[_][left])
left += 1
direction = (direction + 1) % 4 # Change direction
return result
# 示例:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(spiral_order(matrix))
```
如果你想得到逆时针螺旋输出,只需在`direction`变量更新时改变顺序即可。例如,当方向变为0(右->下),则改为(2, 3, 0),依此类推。
阅读全文