【问题标题】:Rotate M*N Matrix (90 degrees) [duplicate]旋转 M*N 矩阵(90 度)[重复]
【发布时间】:2013-08-04 18:45:13
【问题描述】:

如何旋转矩阵

|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 矩阵的。

【问题讨论】:

  • 你有什么尝试吗?表现出一些努力..
  • 这很容易...想想哪个索引在哪里,然后应用。既然你显然不太关心速度,这真的很简单。
  • 你的数据结构是什么样的?
  • 我尝试过的任何一种算法都没有帮助...我尝试了很多
  • 那些链接“如何旋转二维数组?”是方阵!我有非方!这个算法不起作用!

标签: c# algorithm matrix rotation


【解决方案1】:

如果您的矩阵由数组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();
}

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

【讨论】:

  • 这对我不起作用:(
  • 有没有更有效的方法来做这样的事情?以在实时(大)图像处理期间需要将宽度换成高度为例。
  • @SteveCarter,我编辑了我的帖子。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2021-06-30
    • 1970-01-01
    • 2020-09-04
    • 2013-02-09
    • 1970-01-01
    • 2021-10-28
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多