回型矩阵python
时间: 2023-07-01 07:07:03 浏览: 126
下面是一个简单的 Python 代码示例,用于将一个二维数组转换为回型矩阵:
```python
def spiralOrder(matrix):
result = []
if not matrix:
return result
rows, cols = len(matrix), len(matrix[0])
left, right, top, bottom = 0, cols-1, 0, rows-1
while left <= right and top <= bottom:
for j in range(left, right+1):
result.append(matrix[top][j])
for i in range(top+1, bottom+1):
result.append(matrix[i][right])
if top != bottom:
for j in range(right-1, left-1, -1):
result.append(matrix[bottom][j])
if left != right:
for i in range(bottom-1, top, -1):
result.append(matrix[i][left])
left, right, top, bottom = left+1, right-1, top+1, bottom-1
return result
```
示例输入和输出:
输入:
```
matrix = [[1,2,3],[4,5,6],[7,8,9]]
```
输出:
```
[1, 2, 3, 6, 9, 8, 7, 4, 5]
```
阅读全文