c语言编程生成nxn的螺旋方阵
时间: 2024-06-09 17:06:55 浏览: 3
生成nxn的螺旋方阵可以使用以下代码:
```c
#include <stdio.h>
void generateSpiralMatrix(int n) {
int matrix[n][n];
int x = 0, y = 0, num = 1, direction = 0;
int max_x = n - 1, max_y = n - 1, min_x = 0, min_y = 1;
while (num <= n * n) {
matrix[x][y] = num;
// 根据方向移动坐标
if (direction == 0) y++; // 向右走
else if (direction == 1) x++; // 向下走
else if (direction == 2) y--; // 向左走
else if (direction == 3) x--; // 向上走
// 判断是否需要改变方向
if (x == max_x && y == max_y) {
direction = 2;
max_y--;
} else if (x == max_x && y == min_y) {
direction = 3;
max_x--;
} else if (x == min_x && y == min_y) {
direction = 0;
min_y++;
} else if (x == min_x && y == max_y) {
direction = 1;
min_x++;
}
num++;
}
// 输出螺旋方阵
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int n;
printf("请输入方阵大小:");
scanf("%d", &n);
generateSpiralMatrix(n);
return 0;
}
```
代码中使用一个二维数组来存储方阵,同时使用四个变量来记录当前位置、当前走的方向、边界值等信息,根据不同的情况改变方向,最终输出螺旋方阵。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)