矩阵回旋取数python
时间: 2024-12-26 15:20:45 AIGC 浏览: 59
### Python 实现矩阵螺旋顺序取数
#### 方法一:标准求解【检测4个方向】
通过定义上下左右四个边界来控制遍历的方向,在每次完成一条边界的遍历时调整相应的边界值并改变前进方向。
```python
def spiralOrder(matrix):
result = []
if not matrix or not matrix[0]:
return result
rows, columns = len(matrix), len(matrix[0])
up = 0
left = 0
down = rows - 1
right = columns - 1
while True:
# From left to right on the top row.
for col in range(left, right + 1):
result.append(matrix[up][col])
up += 1
if up > down: break
# From top to bottom on the right column.
for row in range(up, down + 1):
result.append(matrix[row][right])
right -= 1
if left > right: break
# From right to left on the bottom row.
for col in range(right, left - 1, -1):
result.append(matrix[down][col])
down -= 1
if up > down: break
# From bottom to top on the left column.
for row in range(down, up - 1, -1):
result.append(matrix[row][left])
left += 1
if left > right: break
return result[^1]
```
此方法的时间复杂度为 O(m * n),其中 m 和 n 分别代表矩阵的行数和列数,因为每个元素仅被访问一次[^2]。
#### 方法二:改进版一【检测2个方向】
简化了方向判断逻辑,只关注当前层的第一个元素和最后一个元素的位置变化规律来进行迭代处理。
```python
def spiral_order_two_directions(matrix):
res = []
while matrix:
res.extend(matrix.pop(0)) # Remove and add first row elements into results list
if matrix and matrix[0]:
for row in matrix:
res.append(row.pop()) # Add last element of each remaining row into results list
if matrix:
res.extend(matrix.pop()[::-1]) # Reverse last row then remove it & append its reversed content into results list
if matrix and matrix[0]:
for row in matrix[::-1]:
if row:
res.append(row.pop(0)) # Pop out first item from every row (in reverse order) until no more items exist
return res[^3]
```
这种方法同样保持了线性的运行效率,并且减少了部分条件分支语句的数量,使得代码更加简洁明了。
阅读全文
相关推荐












