旋转 M*N 矩阵(90 度)

8
如何旋转矩阵?
|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矩阵的。


那很简单...只需考虑哪个索引放在哪里,然后应用即可。由于您显然不太关心速度,所以这非常简单。 - SinisterMJ
你的数据结构是什么样子的? - wjmolina
我尝试过的算法都没有帮助......我尝试了很多。 - Sashko Chehotsky
1
那些关于“如何旋转二维数组”的链接只适用于方阵!我的不是方阵!这个算法不起作用! - Sashko Chehotsky
我在这里回答了:https://dev59.com/vXA85IYBdhLWcg3wCfDm#43694906 - arboreal84
2个回答

19
如果您的矩阵由一个数组matrix[i, j]表示,其中i代表行,j代表列,则实现以下方法:
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;
}

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

编辑:如果这个操作太耗费资源,那么可以尝试改变读取矩阵的方式而不是直接改变矩阵本身。例如,如果我将矩阵显示如下:

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度:

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();
}

这种访问模式也可以抽象成一个类。


这对我不起作用 :( - Saeed mohammadi
有没有更有效的方法来做这样的事情?例如,在实时(大型)图像处理期间需要交换宽度和高度。 - IamSierraCharlie
@SteveCarter,我编辑了我的帖子。 - wjmolina

0
最简单的方法是创建另一个矩阵,其尺寸为N * M(如果原始矩阵为M * N),然后使用嵌套循环将值从一个矩阵复制到另一个矩阵...只需注意正确的索引使用即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接