python实现 螺旋矩阵代码
时间: 2023-09-30 19:06:27 浏览: 53
以下是Python实现螺旋矩阵的代码:
```python
def spiral_matrix(n):
matrix = [[0] * n for i in range(n)]
row, col, direction = 0, 0, 0
directions = [(0, 1), (1, 0), (0, -1), (-1, 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] != 0:
direction = (direction + 1) % 4
row, col = row + directions[direction][0], col + directions[direction][1]
return matrix
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]
```