编程代码螺旋矩阵怎么编

时间:2025-01-23 17:52:09 游戏攻略

```python

def generate_spiral_matrix(n):

创建一个 n x n 的空矩阵

matrix = [ * n for _ in range(n)]

定义初始状态

num = 1

row, col = 0, 0

direction = 0 0表示向右, 1表示向下, 2表示向左, 3表示向上

控制方向与边界

while num <= n * n:

matrix[row][col] = num

num += 1

计算下一个位置

next_row = row + direction

next_col = col + (1 if direction == 0 else 0)

检查边界和下一个格子是否已经填充

if next_row < 0 or next_row >= n or next_col < 0 or next_col >= n or matrix[next_row][next_col] != 0:

变换方向

direction = (direction + 1) % 4

next_row = row + direction

next_col = col + (1 if direction == 0 else 0)

更新位置

row, col = next_row, next_col

return matrix

示例:生成一个 5x5 的螺旋矩阵

spiral_matrix = generate_spiral_matrix(5)

for row in spiral_matrix:

print(row)

```

这个函数首先创建一个 n x n 的空矩阵,然后从左上角开始,按照右、下、左、上的顺序填充数字,直到填充完整个矩阵。在填充过程中,如果下一个位置超出边界或已经被填充,则改变方向。当填充的数字达到 n^2 时,停止填充并返回矩阵。