如果矩阵是由array表示的
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();}该访问模式也可以抽象为一个类。



