如果您的矩阵由数组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();
}
这种访问模式也可以抽象为一个类。