用python写一个螺旋矩阵的函数,可根据输入的数字,生成对应的阶数
时间: 2024-02-03 13:11:36 浏览: 22
以下是一个用 Python 实现生成螺旋矩阵的函数:
```python
def generate_spiral_matrix(n):
matrix = [[0 for i in range(n)] for j in range(n)]
row, col, direction = 0, 0, 0
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for i in range(n*n):
matrix[row][col] = i + 1
next_row, next_col = row + directions[direction][0], col + directions[direction][1]
if 0 <= next_row < n and 0 <= next_col < n and matrix[next_row][next_col] == 0:
row, col = next_row, next_col
else:
direction = (direction + 1) % 4
row, col = row + directions[direction][0], col + directions[direction][1]
return matrix
```
这个函数接受一个整数 n 作为输入,表示生成的螺旋矩阵的阶数。函数会创建一个 n×n 的矩阵,然后按照螺旋的顺序依次填入数字,最后返回生成的矩阵。
示例输入和输出:
```python
>>> generate_spiral_matrix(3)
[[1, 2, 3], [8, 9, 4], [7, 6, 5]]
>>> generate_spiral_matrix(4)
[[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]
```