将基质旋转90度 [英] Rotate a matrix 90 degrees cloclwise

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

问题描述

您好,我正在努力寻找能够将矩阵(多维数组)顺时针旋转90度的算法。我不能使用任何功能(transcope等),基本上我需要自己编写代码。任何提示?





谢谢!

Hello , i'm struggling to find an algorithm that will rotate a matrix (multidimensional array) 90 degrees clockwise. I cant use any functions (transcope etc), Basically i need to write the code on my own. Any tips?


thanks!

推荐答案

for (int i = 0; i < rows; i++)
    {
        for (int j = i + 1; j < col; j++)
        {
            temp = arr[i][j];
            arr[i][j] = arr[j][i];
            arr[j][i] = temp;
        }
    }

    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < col / 2; j++)
        {
            temp = arr[i][j];
            arr[i][j] = arr[i][col - 1 - j];
            arr[i][col - 1 - j] = temp;
        }


试试这样的事情

假设大小为一个大小(nxm)

Try something like this
suppose matrice a of size (n x m)
for(int i=0; i<n;i++)
{
    for(int j=m-1; j>=0;j--)
    {
        printf("%d ", a[j][i]);  //in C
        cout<<a[j][i];          //in C++
    }
    printf("\n"); or  //cout<<endl;
}



如果你想把它保存到其他矩阵:

拿另一个矩阵,比如b大小(nxm)


if you want to save it to other matrix:
Take another matrix, say b of size (n x m)

int x = 0;
for(int i=0; i<n;i++)
{
    for(int j=m-1; j>=0;j--)
    {
        printf("%d ", a[j][i]);  //in C
        cout<<a[j][i];          //in C++
        b[i][x++] = a[j][i]; 
    }
    x = 0;
    printf("\n"); or  //cout<<endl;
}







如果你的矩阵是

1 2

3 4

它将返回

3 1

4 2




if you matrix is
1 2
3 4
it will return
3 1
4 2


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

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