酷代码 AI
菜单
服务商

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

```c #include <stdio.h> int main() { int n; scanf("%d", &n); int matrix[100][100] = {0}; int num = 1; int top = 0, bottom = n - 1; int left = 0, right = n - 1; while (num <= n * n) { for (int i = left; i <= right; i++) { matrix[top][i] = num++; } top++; for (int i = top; i <= bottom; i++) { matrix[i][right] = num++; } right--; for (int i = right; i >= left; i--) { matrix[bottom][i] = num++; } bottom--; for (int i = bottom; i >= top; i--) { matrix[i][left] = num++; } left++; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { printf("%4d", matrix[i][j]); } printf("\n"); } return 0; } ``` [2025-12-31 12:30:51 | AI问答 | 267点数解答]

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