蛇形矩阵

Description

蛇形针回字阵:

3*3:   

 回字阵:

   7 6 5

   8 1 4

   9 2 3

Input

多组数据:

每一行一个正整数n(n为奇数,<26),代表n*n矩阵。

Output

输出回字阵(字段宽度为4).

 

Sample Input

5

Sample Output

 21  20  19  18  17
  22   7   6   5  16
  23   8   1   4  15
  24   9   2   3  14
  25  10  11  12  13
 1 #include<stdio.h>
 2 #include<string.h>
 3 int main()
 4 {
 5     int a[30][30];
 6     int n;
 7     while(scanf("%d",&n)==1)
 8     {
 9         int x,y,tot;
10         memset(a,0,sizeof(a));
11         tot=a[x=n-1][y=0]=n*n;
12 
13         while(tot>1)
14         {
15             while(!a[x-1][y]&&x-1>=0)
16                 a[--x][y]=--tot;
17             while(!a[x][y+1]&&y+1<n)
18                 a[x][++y]=--tot;
19             while(!a[x+1][y]&&x+1<n)
20                 a[++x][y]=--tot;
21             while(!a[x][y-1]&&y-1>=0)
22                 a[x][--y]=--tot;    
23         }
24         for(x=0;x<n;x++)
25         {
26             for(y=0;y<n;y++)
27                 printf("%4d",a[x][y]);
28             printf("
");
29         
30         }
31     }
32 }
原文地址:https://www.cnblogs.com/a1225234/p/4486803.html