蛇型数组

来源:互联网 发布:口腔医生收入 知乎 编辑:程序博客网 时间:2024/04/28 12:22

直接上代码:

[cpp] view plaincopy
  1. #include <malloc.h>  
  2. #include <stdio.h>  
  3.   
  4. int main(void)  
  5. {  
  6.     //用户输入的值,创建n*n的矩阵  
  7.     int n;  
  8.     //蛇形从1开始计数  
  9.     int count = 1;  
  10.     //a[x][y],x是二维数组的第一个下标,y是第二个。  
  11.     //round是蛇形矩阵的第几圈,从0开始。  
  12.     int x,y,round;  
  13.   
  14.     scanf("%d",&n);   
  15.     int (*a)[n] = calloc(n*n,sizeof(int));  
  16.       
  17.     //如果n是1,则直接输出。  
  18.     if(n == 1){  
  19.         a[0][0] = count;  
  20.     }else{  
  21.     //下面以n=5为例  
  22.     //一共有2(5/2)圈蛇形  
  23.     for(round=0; round<n/2; round++){  
  24.         /* 以下循环执行后输出如下: 
  25.             1 2 3 4 5 
  26.         */  
  27.       
  28.         x = round;  
  29.         for(y=round;y<n-round;y++){  
  30.             a[x][y]=count;  
  31.             count++;  
  32.         }  
  33.         /* 以下循环执行后输出如下: 
  34.             1 2 3 4 5 
  35.                     6 
  36.                     7 
  37.                     8 
  38.         */  
  39.         y = n - round - 1;  
  40.         for(x=round+1;x<n-round-1;x++){  
  41.             a[x][y]=count;  
  42.             count++;  
  43.         }  
  44.           
  45.         /* 以下循环执行后输出如下: 
  46.             1  2  3  4  5 
  47.                         6 
  48.                         7 
  49.                         8 
  50.             13 12 11 10 9    
  51.         */  
  52.         x = n - round - 1;  
  53.         for(y=n-round-1;y>=round;y--){  
  54.             a[x][y]=count;  
  55.             count++;  
  56.         }  
  57.           
  58.         /* 以下循环执行后输出如下: 
  59.             1  2  3  4  5 
  60.             16          6 
  61.             15          7 
  62.             14          8 
  63.             13 12 11 10 9 
  64.         */  
  65.         y = round;  
  66.         for(x=n-round-1-1;x>round;x--){  
  67.             a[x][y]=count;  
  68.             count++;  
  69.         }  
  70.     }  
  71.     /* 上面的大循环执行后输出如下: 
  72.             1  2  3  4  5 
  73.             16 17 18 19 6 
  74.             15 24    20 7 
  75.             14 23 22 21 8 
  76.             13 12 11 10 9 
  77.         */  
  78.     if(n%2 == 1){  
  79.         //如果n值奇数,将最中间的空填上  
  80.         a[n/2][n/2] = count;  
  81.     }  
  82.     }  
  83.     //打印矩阵  
  84.     for(x=0;x<n;x++){  
  85.         for(y=0;y<n;y++){  
  86.             printf("%d ",a[x][y]);  
  87.         }  
  88.         printf("\n");  
  89.     }  
  90.     printf("\n");  
  91.   
  92.     free(a);  
  93.     return 0;