以下是5✖️5的螺旋方阵,编程生成n✖️n的螺旋方阵
时间: 2023-12-10 17:39:54 浏览: 160
生成n✖️n的螺旋方阵可以采用模拟螺旋填充的方式,具体实现如下(使用 Python 语言):
```python
def generate_spiral_matrix(n):
# 初始化矩阵
matrix = [[0] * n for _ in range(n)]
# 定义初始值
num, direction = 1, 0
x, y = 0, 0
# 填充数字
for i in range(n * n):
matrix[x][y] = num
if direction == 0: # 向右填充
if y + 1 < n and matrix[x][y + 1] == 0:
y += 1
else:
direction = 1
x += 1
elif direction == 1: # 向下填充
if x + 1 < n and matrix[x + 1][y] == 0:
x += 1
else:
direction = 2
y -= 1
elif direction == 2: # 向左填充
if y - 1 >= 0 and matrix[x][y - 1] == 0:
y -= 1
else:
direction = 3
x -= 1
else: # 向上填充
if x - 1 >= 0 and matrix[x - 1][y] == 0:
x -= 1
else:
direction = 0
y += 1
num += 1
return matrix
```
该函数接受一个整数参数n,返回一个n✖️n的螺旋方阵。例如,`generate_spiral_matrix(5)`将返回以下方阵:
```
[[1, 2, 3, 4, 5],
[16, 17, 18, 19, 6],
[15, 24, 25, 20, 7],
[14, 23, 22, 21, 8],
[13, 12, 11, 10, 9]]
```
阅读全文