C - 矩阵旋转 [英] C - matrix rotation

查看:37
本文介绍了C - 矩阵旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C 编写程序,我需要一个 M x N 矩阵来顺时针旋转.我尝试了一些算法,但它们只适用于 N x N 矩阵.

I'm writing a program in C and I need a M x N matrix to rotate clockwise. I tried some algorithms, but they only work in N x N matrices.

矩阵 {(1,4), (2,5), (3,6)} 应该变成 {(3,2,1), (6,5,4)}:

1 4
2 5  ->  3 2 1
3 6      6 5 4

我写了这段代码来转置矩阵,现在我不知道如何交换列:

I wrote this piece of code to transpose the matrix, and now I don't know how to swap the columns:

void transpose(int matrix[MAX][MAX], int m, int n)
{
    int transpose[MAX][MAX], d, c;

    for (c = 0; c < m; c++)
      for( d = 0 ; d < n ; d++)
         transpose[d][c] = matrix[c][d];

    for (c = 0; c < n; c++)
        for(d = 0; d < m; d++)
            matrix[c][d] = transpose[c][d];
}

推荐答案

这是一个想法.我已经在 J​​ava 中实现了它,但它应该在 C 中以相同的方式工作.这个想法是从末尾读取主要行的数组,并从头开始主要明智地填充另一个数组列.

Here's an idea. I've implemented it in Java, but it should work in the same manner in C. The idea is to read the array row major wise from the end, and fill the other array column major wise, from the beginning.

    int a[][]={{1,4},{2,5},{3,6}};
    int m=3,n=2;   //you will need to edit this and actually calculate rows and columns.

    int b[][]=new int[n][m];

    for(int i=m-1; i>=0; i--)
      for(int j=0; j<n; j++)
        b[j][m-i-1]=a[i][j];


    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++)
           System.out.print(b[i][j]+"\t");
        System.out.println();
    }

输出:https://ideone.com/TveuB5

这篇关于C - 矩阵旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆