C 蛇形填图

  1. 描述
  2. 在n*n方陈里填入1,2,...,n*n,要求填成蛇形。
  3. 例如n=4时方陈为:
  4. 10 11 12 1
  5. 9 16 13 2
  6. 8 15 14 3
  7. 7 6 5 4
  8. 输入 直接输入方陈的维数,即n的值。(n<=100) 输出
  9. 输出结果是蛇形方陈。
  10. 样例输入
  11. 3
  12. 样例输出
  13. 7 8 1
  14. 6 9 2
  15. 5 4 3
 1 #include <stdio.h>
 2 #include<string.h>
 3 #define maxn 102
 4 int a[maxn][maxn];
 5 int main()
 6 { 
 7 int n,x,y,tot=0; 
 8 scanf("%d",&n); 
 9 memset(a,0,sizeof(a)); 
10 tot=a[x=0][y=n-1]=1; 
11 while(tot<n*n) //计算二维数组存储值
12 { 
13 while(x+1<n&&!a[x+1][y])a[++x][y]=++tot; 
14 while(y-1>=0&&!a[x][y-1])a[x][--y]=++tot; 
15 while(x-1>=0&&!a[x-1][y])a[--x][y]=++tot; 
16 while(y+1<n &&!a[x][y+1])a[x][++y]=++tot; 
17 }
18 for(x=0;x<n;x++)
19 { 
20 for(y=0;y<n;y++) 
21 { 
22 printf("%d",a[x][y]); 
23 } 
24 printf("
");
25 }
26 return 0;
27 }
View Code
原文地址:https://www.cnblogs.com/HorseKing/p/3550596.html