【发布时间】:2018-04-04 01:14:53
【问题描述】:
我有一个旋转动态平方数组的类。我只需要平方旋转。目前只能向左旋转。我还需要它向右旋转。
这个答案提供了一个逆时针旋转它的解决方案,我的修改版本如下满足我的需要,但我不知道如何做相反的事情。
Rotate M*N Matrix (90 degrees)
我可以调用 RotateLeft() 3x,但当然,这是低效的。我想了解另一种解决方案。
我的代码:
public void RotateLeft()
{
m_array = RotateMatrixCounterClockwise(m_array, m_width, m_height);
}
public void RotateRight()
{
}
public static T[] RotateMatrixCounterClockwise(T[] oldMatrix, int width, int height)
{
T[] newMatrix = new T[width * height];
int newColumn, newRow = 0;
for (int oldColumn = height - 1; oldColumn >= 0; oldColumn--)
{
newColumn = 0;
for (int oldRow = 0; oldRow < width; oldRow++)
{
newMatrix[newRow * width + newColumn] = oldMatrix[oldRow * width + oldColumn];
newColumn++;
}
newRow++;
}
return newMatrix;
}
解决方案:
感谢 Daniel,此代码将来可能对其他人有用。唯一改变的是内部块:
newMatrix[oldRow * width + oldColumn] = oldMatrix[newRow * width + newColumn];
完整代码:
public static T[] RotateMatrixClockwise(T[] oldMatrix, int width, int height)
{
T[] newMatrix = new T[width * height];
int newColumn, newRow = 0;
for (int oldColumn = height - 1; oldColumn >= 0; oldColumn--)
{
newColumn = 0;
for (int oldRow = 0; oldRow < width; oldRow++)
{
newMatrix[oldRow * width + oldColumn] = oldMatrix[newRow * width + newColumn];
newColumn++;
}
newRow++;
}
return newMatrix;
}
【问题讨论】:
-
我对这里术语的使用有点困惑。给定类似
int[]{ 11,12, 21, 22, 31, 32, 41, 42, 51, 52 }的内容,您希望在这两种情况下的结果是什么,宽度 = 2,高度 = 5...如果这有意义的话 -
好吧,我现在真的很困惑,你使用的是单维数组还是多维数组
-
@TheGeneral:他通过连接所有行将矩阵存储在一维数组中。
标签: c#