python 按回型打印矩阵
时间: 2023-10-03 17:03:26 浏览: 273
以下是按回型打印矩阵的 Python 代码:
```python
def print_matrix_in_spiral(matrix):
if not matrix:
return
rows = len(matrix)
cols = len(matrix[0])
top = 0
bottom = rows - 1
left = 0
right = cols - 1
while left <= right and top <= bottom:
# Print top row
for i in range(left, right + 1):
print(matrix[top][i], end=" ")
top += 1
# Print right column
for i in range(top, bottom + 1):
print(matrix[i][right], end=" ")
right -= 1
# Print bottom row
if top <= bottom:
for i in range(right, left - 1, -1):
print(matrix[bottom][i], end=" ")
bottom -= 1
# Print left column
if left <= right:
for i in range(bottom, top - 1, -1):
print(matrix[i][left], end=" ")
left += 1
```
该函数将一个二维矩阵作为输入,并按回型顺序打印矩阵中的所有元素。首先,确定矩阵的上下左右四个边界,然后按顺序打印上边界、右边界、下边界和左边界。每次打印完一个边界后,相应的边界向内收缩一格。循环继续直到所有元素都被打印完。
阅读全文