weixin_44647325 2019-10-28 14:49 采纳率: 20%
浏览 307

如何把一个矩阵由内到外顺时针cout出来

如何把一个矩阵由内到外顺时针cout出来?C++

就像给了一个已经从矩阵中心向外旋转好了的矩阵

图一图片说明

然后如何cout 这个矩阵旋转之前的矩阵

就是这样

图二图片说明

图一旋转的方式图片说明

  • 写回答

1条回答 默认 最新

  • bobhuang 2019-10-28 17:09
    关注
    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAX_N 10
    
    void init_met(int *m, int n)
    {
        int i;
    
        for (i = 0; i < n * n; ++i) {
            m[i] = i + 1;
        }
    }
    
    void prt_met_xy(int *m, int n, int x, int y)
    {
        printf("%d,%d: %d \n", x, y, m[(y-1) * n + x - 1]);
    }
    
    void prt_met(int *m, int n)
    {
        int x, y;
        int start, end; // 当前圈的边界
        int r; // radius
        int n2; // n / 2
        int p; // position
    
        n2 = (n + 1) / 2;
        x = y = n2; // 坐标从中心位置开始
        r = 1; // 半径从1开始
    
        // 输出当前点
        prt_met_xy(m, n, x, y);
        // 右移一个位置
        x += 1;
        for (r = 1; r < n2; ++r) {
            start = (n - 2 * r + 1) / 2;
            end = (n + 2 * r + 1) / 2;
            // 向下
            for (; y < end; ++y) {
                prt_met_xy(m, n, x, y);
            }
            // 向左
            for (; x > start; --x) {
                prt_met_xy(m, n, x, y);
            }
            // 向上
            for (; y > start; --y) {
                prt_met_xy(m, n, x, y);
            }
            // 向右, 多走一格
            for (; x <= end; ++x) {
                prt_met_xy(m, n, x, y);
            }
        }
    }
    
    int main()
    {
        int n = 0;
        int *m;
    
        printf("input N:");
        scanf("%d", &n);
    
        // 算法只计算奇数的N
        if (n % 2 == 0 || n > MAX_N) {
            printf("N must be odd and less then %d\n", MAX_N);
        } else {
            m = (int*)malloc(sizeof(int) * n * n);
            if (NULL == m) {
                return 0;
            } else {
                init_met(m, n);
                prt_met(m, n);
                free(m);
            }
        }
    
        return 0;
    }
    
    
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题