zoukankan      html  css  js  c++  java
  • 基础练习 回形取数

    问题描述
      回形取数就是沿矩阵的边取数,若当前方向上无数可取或已经取过,则左转90度。一开始位于矩阵左上角,方向向下。
    输入格式
      输入第一行是两个不超过200的正整数m, n,表示矩阵的行和列。接下来m行每行n个整数,表示这个矩阵。
    输出格式
      输出只有一行,共mn个数,为输入矩阵回形取数得到的结果。数之间用一个空格分隔,行末不要有多余的空格。
    样例输入
    3 3
    1 2 3
    4 5 6
    7 8 9
    样例输出
    1 4 7 8 9 6 3 2 5
    样例输入
    3 2
    1 2
    3 4
    5 6
    样例输出
    1 3 5 6 4 2
     
    思路:以一个circle为循环标记,类似于往里边绕圈的感觉,每绕一圈,要遍历的元素显然越来越少,用四个for循环分别输出左边下边右边上边,不过这四种输出的方式比较难想,以 count < col * row 为循环结束标志即可。
     1 #include<stdio.h>
     2 #include<string.h>
     3 #include<stdlib.h>
     4 
     5 int main(void)
     6 {
     7     int row, col;
     8     int i, j,k,h;
     9     int** matrix;
    10 
    11     scanf("%d %d", &row, &col);
    12     matrix = (int **)malloc(sizeof(int*) * row);
    13     for (i = 0; i < row; i++)
    14     {
    15         matrix[i] = (int *)malloc(sizeof(int) * col);
    16     }
    17     for (i = 0; i < row; i++)
    18     {
    19         for (j = 0; j < col; j++)
    20         {
    21             scanf("%d", &matrix[i][j]);
    22         }
    23     }
    24 
    25     int circle = 0;
    26     int count = 0;
    27 
    28     while (count < row * col)
    29     {
    30         for (i = circle; i < row - circle && count < row * col; i++) //左边
    31         {
    32             printf("%d ", matrix[i][circle]);
    33             count += 1;
    34         }
    35         for (j = circle + 1; j < col - circle && count < row * col; j++) //下边
    36         {
    37             printf("%d ", matrix[row - 1 - circle][j]);
    38             count += 1;
    39         }
    40         for (k = row - 2 - circle; k >= circle && count < row * col; k--) //右边
    41         {
    42             printf("%d ", matrix[k][col - 1 - circle]);
    43             count += 1;
    44         }
    45         for (h = col - 2 - circle; h >= circle + 1 && count < row * col; h--) //上边
    46         {
    47             printf("%d ", matrix[circle][h]);
    48             count += 1;
    49         }
    50         circle += 1;
    51     }
    52     return 0;
    53 }
     
  • 相关阅读:
    【EXCEL】乱数関数集合
    PHP 获取当前时间前52周 12个月 4个季度
    python 清理没有过期时间的redis
    yii2 使用mongo查询(包含like查询)
    crontab 时间详解
    安装 cronsun
    php的加密&解密 (压缩数据) gzcompress & gzuncompress
    三数之和
    贪心算法解决集合覆盖问题
    KMP算法实现字符串匹配
  • 原文地址:https://www.cnblogs.com/ZhengLijie/p/12642556.html
Copyright © 2011-2022 走看看