回型矩阵代码
时间: 2023-07-09 12:06:00 浏览: 169
回型矩阵填充代码
以下是一个 Python 实现的回型矩阵代码,可以根据输入的矩阵大小自动生成回型矩阵:
```python
def spiral_matrix(n):
# 初始化矩阵
matrix = [[0 for i in range(n)] for j in range(n)]
# 定义四个方向的移动
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
# 初始位置和方向
row, col, direction = 0, 0, 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 next_row < 0 or next_row >= n or next_col < 0 or next_col >= n or matrix[next_row][next_col]:
direction = (direction + 1) % 4
# 更新位置
row, col = row + directions[direction][0], col + directions[direction][1]
return matrix
# 测试代码
n = 5
spiral = spiral_matrix(n)
for i in range(n):
print(spiral[i])
```
输出结果为:
```
[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]
```
这就是一个 5x5 的回型矩阵。
阅读全文