zoukankan      html  css  js  c++  java
  • 打印螺旋矩阵

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #include<math.h>
     4 
     5 #define MAX 64
     6 
     7 void initArray(int array[][MAX], int n);
     8 void printArray(int array[][MAX], int n);
     9 
    10 int main()
    11 {
    12     int n;
    13     int array[MAX][MAX];
    14     printf("Input n:
    ");
    15     scanf_s("%d",&n);
    16     initArray(array,n);
    17     printArray(array,n);
    18     system("pause");
    19     return 0;
    20 }
    21 
    22 void initArray(int array[][MAX], int n)
    23 {
    24     int cnt = 1;//记录要打印的数
    25     int i,j;//行列下标
    26     int step;//打印数组一个方向上的数的下标
    27     int step_cnt = 1;//打印数组一个方向上的数的个数
    28 
    29     i = n>>1;
    30     j = n>>1;
    31 
    32     array[i][j] = 1;//将最中间元素置1
    33 
    34     while(cnt <= n*n)//cnt <= pow((float)n,2)
    35     {
    36         //从下往上
    37         for(step = 0; step < step_cnt; step++, i--)
    38             array[i-1][j] = ++cnt;
    39         if(cnt > n*n)
    40             break;
    41 
    42         //从右往左
    43         for(step = 0; step < step_cnt; step++,j--)
    44             array[i][j-1] = ++cnt;
    45         if(cnt > n*n)
    46             break;
    47 
    48         step_cnt++;
    49 
    50         //从上往下
    51         for(step = 0; step < step_cnt; step++,i++)
    52             array[i+1][j] = ++cnt;
    53         if(cnt > n*n)
    54             break;
    55 
    56         //从左往右
    57         for(step = 0; step < step_cnt; step++,j++)
    58             array[i][j+1] = ++cnt;
    59 
    60         step_cnt++;
    61     }
    62 }
    63 
    64 void printArray(int array[][MAX], int n)
    65 {
    66     int i, j;
    67     for(i = 0; i < n; i++)
    68     {
    69         for(j = 0; j < n; j++)
    70             printf("%3d",array[i][j]);
    71         printf("
    ");
    72     }
    73 }

  • 相关阅读:
    BestCoder Round #84
    codeforces#689BMike and Shortcuts
    POJ2985 并查集+线段树 求第k大的数
    Trie树模板 POJ1056
    新建zabbix数据库
    python输出菱形
    wmi获取计算机信息
    python测试IP地址是否ping通
    手机安装python环境
    Centos 8 安装zabbix 爬坑
  • 原文地址:https://www.cnblogs.com/cpsmile/p/4776796.html
Copyright © 2011-2022 走看看