蛇形填数,输入一个整数
n
n
n,安装蛇形填写
n
×
n
n \times n
n×n
引入头文件#include <stdlib.h>
,使用malloc()
动态分配内存,free()
函数释放内存。
malloc()函数为二维数组分配空间步骤:
- 分配第一维的大小
- 循环分配每一维的大小
int **p
p = (int **)malloc(n *sizeof(int*));/*为二维数组分配n行*/
for (int i = 0; i < n; ++i) {
p[i] = (int*)malloc(sizeof(int) * n);/*为每列分配n个大小空间*/
}
然后对二维数组进行初始化:
for (int i = 0; i < n; ++i){
for (int j = 0; j < n; ++j){
p[i][j] = 0;
}
}
使用free()
函数释放内存:
for (int i = 0; i < n; ++i){
free(p[i]);
}
free(p);
完整代码:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n,**p,x,y,total;
x = y = 0;
scanf("%d",&n);
p = (int **)malloc(n *sizeof(int*));
for (int i = 0; i < n; ++i) {
p[i] = (int*)malloc(sizeof(int) * n);
}
for (int i = 0; i < n; ++i){
for (int j = 0; j < n; ++j){
p[i][j] = 0;
}
}
total = p[0][0] = 1;
while(total < n * n){
while(y+1 < n && !p[x][y+1]){
p[x][++y] = ++total;
}
while(x+1 < n && !p[x+1][y]){
p[++x][y] = ++total;
}
while(y-1 < n && !p[x][y-1]){
p[x][--y] = ++total;
}
while(x-1 < n && !p[x-1][y]){
p[--x][y] = ++total;
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
printf("%-5d",p[i][j]);
}
printf("\n");
}
for (int i = 0; i < n; ++i){
free(p[i]);
}
free(p);
return 0;
}
输入:
4
输出:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7