如何用Python编写实现乌拉姆螺旋矩阵
时间: 2024-12-19 09:20:33 浏览: 1
乌拉姆螺旋矩阵是一个特殊的数阵,它按照一定的规则排列数字,通常用于展示数字的模式和规律。以下是使用Python编写生成乌拉姆螺旋矩阵的一种方法:
```python
def generate_spiral(n):
matrix = [[0] * n for _ in range(n)]
num = 1
dx, dy = [0, 1], [1, 0]
row, col = 0, 0
while num <= n*n:
matrix[row][col] = num
num += 1
# 更新方向并移动
direction_changes = 4 - ((row + col) % 4)
for _ in range(direction_changes):
next_dir = (directions.index(dy) + 1) % 4
new_row, new_col = row + dx[next_dir], col + dy[next_dir]
if 0 <= new_row < n and 0 <= new_col < n and not matrix[new_row][new_col]:
row, col = new_row, new_col
dx, dy = [0, 1, 0, -1][next_dir:], [1, 0, -1, 0][next_dir:]
else:
row, col = row - dx[direction_changes-1], col - dy[direction_changes-1]
return matrix
# 示例
n = 5
spiral_matrix = generate_spiral(n)
for row in spiral_matrix:
print(row)
阅读全文