帮我写一个螺旋矩阵的代码。
时间: 2023-08-20 16:09:07 浏览: 79
螺旋矩阵代码
好的,下面是一个Python实现的螺旋矩阵代码:
```python
def spiral_matrix(n):
matrix = [[0] * n for _ in range(n)]
count = 1
row, col = 0, 0
for i in range((n + 1) // 2):
# 上边
for j in range(col, n - col):
matrix[row][j] = count
count += 1
# 右边
for j in range(row + 1, n - row):
matrix[j][n - col - 1] = count
count += 1
# 下边
for j in range(n - col - 2, col - 1, -1):
matrix[n - row - 1][j] = count
count += 1
# 左边
for j in range(n - row - 2, row, -1):
matrix[j][col] = count
count += 1
row += 1
col += 1
return matrix
```
使用方法:
```python
n = 5
matrix = spiral_matrix(n)
for row in matrix:
print(row)
```
输出结果:
```
[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]
```
阅读全文