python二维数组回形遍历
时间: 2023-12-27 08:24:42 浏览: 81
以下是Python实现二维数组回形遍历的代码示例:
```python
def spiralOrder(matrix):
if not matrix:
return []
m, n = len(matrix), len(matrix[0])
left, right, top, bottom = 0, n - 1, 0, m - 1
res = []
while left <= right and top <= bottom:
for i in range(left, right + 1):
res.append(matrix[top][i])
top += 1
for i in range(top, bottom + 1):
res.append(matrix[i][right])
right -= 1
if top <= bottom:
for i in range(right, left - 1, -1):
res.append(matrix[bottom][i])
bottom -= 1
if left <= right:
for i in range(bottom, top - 1, -1):
res.append(matrix[i][left])
left += 1
return res
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = spiralOrder(matrix)
print(result) # 输出:[1, 2, 3, 6, 9, 8, 7, 4, 5]
```
阅读全文