旋转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矩阵。
如果矩阵由数组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; }
这适用于各种尺寸的矩阵。
最简单的方法是创建另一个矩阵,其尺寸为N * M(如果原始具有M * N),然后使用嵌套循环将值从一个矩阵复制到另一个矩阵……请记住正确的索引用法。