旋转 M*N 矩阵(90 度) [英] Rotate M*N Matrix (90 degrees)

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

问题描述

如何旋转矩阵

|3 4 5 6 8|
|5 4 3 2 6|
|3 3 7 8 9|

|8 6 9|            
|6 2 8|
|5 3 7|
|4 4 3|
|3 5 3|

因为我见过的所有算法都是针对 N*N 矩阵的.

Because all algorithms I've seen was for N*N matrix.

推荐答案

如果你的矩阵是用数组 matrix[i, j] 表示的,其中 i 是行和 j 是列,然后实现以下方法:

If your matrix is represented by an array matrix[i, j], where the i are the rows and the j are the columns, then implement the following method:

static int[,] RotateMatrixCounterClockwise(int[,] oldMatrix)
{
    int[,] newMatrix = new int[oldMatrix.GetLength(1), oldMatrix.GetLength(0)];
    int newColumn, newRow = 0;
    for (int oldColumn = oldMatrix.GetLength(1) - 1; oldColumn >= 0; oldColumn--)
    {
        newColumn = 0;
        for (int oldRow = 0; oldRow < oldMatrix.GetLength(0); oldRow++)
        {
            newMatrix[newRow, newColumn] = oldMatrix[oldRow, oldColumn];
            newColumn++;
        }
        newRow++;
    }
    return newMatrix;
}

这适用于所有大小的矩阵.

This works for matrices of all sizes.

编辑:如果这个操作代价太大,那么可以尝试改变读取矩阵的方式,而不是改变矩阵本身.例如,如果我按如下方式显示矩阵:

Edit: If this operation is too expensive, then one could try changing the way one reads the matrix instead of changing the matrix itself. For example, if I am displaying the matrix as follows:

for (int row = 0; row < matrix.GetLength(0); row++)
{
    for (int col = 0; col < matrix.GetLength(1); col++)
    {
        Console.Write(matrix[row, col] + " ");
    }

    Console.WriteLine();
}

然后我可以通过改变读取矩阵的方式来表示逆时针旋转 90 度:

then I could represent a 90-degree counterclockwise rotation by changing the way I read the matrix:

for (int col = matrix.GetLength(1) - 1; col >= 0; col--)
{
    for (int row = 0; row < matrix.GetLength(0); row++)
    {
        Console.Write(matrix[row, col] + " ");
    }

    Console.WriteLine();
}

这种访问模式也可以抽象为一个类.

This access pattern could be abstracted in a class, too.

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

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