给定一个捏*n的矩阵,其中n小于等于50。按蛇形打印矩阵的元素
时间: 2023-11-27 21:53:36 浏览: 27
以下是Python实现的代码:
```python
def print_matrix_spiral(matrix):
m = len(matrix)
n = len(matrix[0])
top = 0
bottom = m - 1
left = 0
right = n - 1
direction = "right"
result = []
while top <= bottom and left <= right:
if direction == "right":
for i in range(left, right + 1):
result.append(matrix[top][i])
top += 1
direction = "down"
elif direction == "down":
for i in range(top, bottom + 1):
result.append(matrix[i][right])
right -= 1
direction = "left"
elif direction == "left":
for i in range(right, left - 1, -1):
result.append(matrix[bottom][i])
bottom -= 1
direction = "up"
else:
for i in range(bottom, top - 1, -1):
result.append(matrix[i][left])
left += 1
direction = "right"
return result
```
函数`print_matrix_spiral`接收一个矩阵作为参数,返回按蛇形打印矩阵元素的结果。该函数使用四个变量`top`、`bottom`、`left`和`right`来表示矩阵的四个边界,变量`direction`表示当前打印方向。随着打印的进行,边界逐渐收缩,直到所有元素都被打印出来。