Loading

蛇形填数

给定一个 n , 在  n * n 的方阵中填入 1 ,2, 3,……,n * n,  要求填成蛇形。

 

例如在 n = 5 时 , 如下所示: 

13   14   15   16   1

12   23   24   17   2

11   22   25   18   3

10   21   20   19   4

  9     8     7     6   5

 1 #include<stdio.h>
 2 #include<string.h>
 3 int main()
 4 {
 5     int n,x=0,y=0,co=1;//co为计数
 6     scanf("%d",&n);
 7     int a[n][n];
 8     memset(a,0,sizeof(a));
 9     a[x][y]=1;
10     while(co!=n*n)
11     {
12         while(x+1<n&&a[x+1][y]==0)
13         {
14             a[++x][y]=++co;
15         }
16         while(y+1<n&&a[x][y+1]==0)
17         {
18             a[x][++y]=++co;
19 
20         }
21         while(x-1>=0&&a[x-1][y]==0)
22         {
23             a[--x][y]=++co;
24         }
25         while(y-1>=0&&a[x][y-1]==0)
26         {
27             a[x][--y]=++co;
28         }
29         if(co==n*n)
30             break;
31     }
32     for(int i=0; i<n; i++)
33     {
34         for(int j=0; j<n; j++)
35         {
36             printf("%3d",a[i][j]);
37         }
38         printf("\n");
39 
40     }
41     return 0;
42 }
View Code

甚至可以利用越界的数组为未知数来省略越界判断

 1 #include<stdio.h>
 2 #include<string.h>
 3 int main()
 4 {
 5     int n,x=0,y=0,co=1;//co为计数
 6     scanf("%d",&n);
 7     int a[n][n];
 8     memset(a,0,sizeof(a));
 9     a[x][y]=1;
10     while(co!=n*n)
11     {
12         while(a[x+1][y]==0)
13         {
14             a[++x][y]=++co;
15         }
16         while(a[x][y+1]==0)
17         {
18             a[x][++y]=++co;
19 
20         }
21         while(a[x-1][y]==0)
22         {
23             a[--x][y]=++co;
24         }
25         while(a[x][y-1]==0)
26         {
27             a[x][--y]=++co;
28         }
29         if(co==n*n)
30             break;
31     }
32     for(int i=0; i<n; i++)
33     {
34         for(int j=0; j<n; j++)
35         {
36             printf("%3d",a[i][j]);
37         }
38         printf("\n");
39 
40     }
41     return 0;
42 }
View Code

进阶为在外层套上m层0

 

 1 #include<stdio.h>
 2 #include<string.h>
 3 int main()
 4 {
 5     int n,m,co=1;//co为计数
 6     scanf("%d%d",&n,&m);//n
 7     int a[n+2*m][n+2*m];
 8     int x=m,y=m;
 9     memset(a,0,sizeof(a));
10     a[x][y]=1;
11     while(co!=n*n)
12     {
13         while(x+1<n+m&&a[x+1][y]==0)
14         {
15             a[++x][y]=++co;
16         }
17         while(y+1<n+m&&a[x][y+1]==0)
18         {
19             a[x][++y]=++co;
20 
21         }
22         while(x-1>=m&&a[x-1][y]==0)
23         {
24             a[--x][y]=++co;
25         }
26         while(y-1>=m&&a[x][y-1]==0)
27         {
28             a[x][--y]=++co;
29         }
30         if(co==n*n)
31             break;
32     }
33     for(int i=0; i<n+2*m; i++)
34     {
35         for(int j=0; j<n+2*m; j++)
36         {
37             printf("%3d",a[i][j]);
38         }
39         printf("\n");
40 
41     }
42     return 0;
43 }
View Code

 

posted @ 2018-11-24 10:36  沉云  阅读(234)  评论(0编辑  收藏  举报