• 打印螺旋矩阵


     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 }

  • 相关阅读:
    [Leetcode] Flatten Binary Tree to Linked List
    [Leetcode] Letter Combinations of a Phone Number
    [Leetcode] Distinct Subsequences
    [Leetcode] Partition List
    [Leetcode] Reverse Linked List II
    [Leetcode] Swap Nodes in Pairs
    [Jobdu] 题目1391:顺时针打印矩阵
    [Jobdu] 题目1369:字符串的排列
    [Jobdu] 题目1283:第一个只出现一次的字符
    如何应用ML的建议-下
  • 原文地址:https://www.cnblogs.com/cpsmile/p/4776796.html
Copyright © 2020-2023  润新知