python二维数组回形遍历
时间: 2023-12-27 15:24:42 浏览: 89
解决Python二维数组赋值问题
5星 · 资源好评率100%
以下是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]
```
阅读全文