下面是一个5阶的螺旋方阵。编写程序打印此形式的n(n<10)阶的方阵。 (顺时针方向旋进) 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
时间: 2023-03-21 21:02:53 浏览: 91
以下是一个用Python编写的打印螺旋方阵的程序,可以根据输入的阶数来打印对应阶数的螺旋方阵:
```python
def print_spiral_matrix(n):
matrix = [[0] * n for i in range(n)]
count = 1
row_start, row_end, col_start, col_end = 0, n-1, 0, n-1
while row_start <= row_end and col_start <= col_end:
for i in range(col_start, col_end+1):
matrix[row_start][i] = count
count += 1
row_start += 1
for i in range(row_start, row_end+1):
matrix[i][col_end] = count
count += 1
col_end -= 1
if row_start <= row_end:
for i in range(col_end, col_start-1, -1):
matrix[row_end][i] = count
count += 1
row_end -= 1
if col_start <= col_end:
for i in range(row_end, row_start-1, -1):
matrix[i][col_start] = count
count += 1
col_start += 1
for i in range(n):
for j in range(n):
print(matrix[i][j], end='\t')
print()
# 测试
print_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
```
希望这个程序对你有帮助。
阅读全文