酷代码 AI
菜单
服务商

给出一个不大于 100 的正整数 n,输出 n×n 的蛇形方阵。 从左上角填上 1 开始,顺时针方向依次填入数字,如同样例所示。注意每个数字有都会占用 4 个字符,后面使用空格补齐。 样例输入 复制 3 样例输出 复制 1 2 3 8 9 4 7 6 5

```python n = int(input()) matrix = [[0] * n for _ in range(n)] directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] x, y, d = 0, 0, 0 for num in range(1, n * n + 1): matrix[x][y] = num nx, ny = x + directions[d][0], y + directions[d][1] if not (0 <= nx < n and 0 <= ny < n and matrix[nx][ny] == 0): d = (d + 1) % 4 nx, ny = x + directions[d][0], y + directions[d][1] x, y = nx, ny for row in matrix: print(''.join(f'{num:<4d}' for num in row)) ``` [2026-01-04 12:10:01 | AI问答 | 196点数解答]

相关提问
发财导航,免费问AI
实用工具查看更多