给一个整数n,输出n*n的回形矩阵
时间: 2023-05-30 20:01:47 浏览: 146
以下是Python实现:
```python
def spiral_matrix(n):
matrix = [[0] * n for i in range(n)]
num = 1
row = col = 0
directions = [(0,1), (1,0), (0,-1), (-1,0)]
direction_index = 0
for i in range(n*n):
matrix[row][col] = num
num += 1
next_row = row + directions[direction_index][0]
next_col = col + directions[direction_index][1]
if next_row < 0 or next_row >= n or next_col < 0 or next_col >= n or matrix[next_row][next_col] != 0:
direction_index = (direction_index + 1) % 4
row += directions[direction_index][0]
col += directions[direction_index][1]
return matrix
n = int(input("请输入整数n:"))
matrix = spiral_matrix(n)
for row in matrix:
print(row)
```
该函数首先创建了一个n*n的矩阵,然后按照从左到右、从上到下、从右到左、从下到上的顺序依次填入数字。当到达边界或者遇到已经填入数字的格子时,就改变方向。最后返回填好的矩阵。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)