如何旋转矩阵?
|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矩阵的。
|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;
}
这适用于所有大小的矩阵。
编辑:如果这个操作太耗费资源,那么可以尝试改变读取矩阵的方式而不是直接改变矩阵本身。例如,如果我将矩阵显示如下:
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();
}
这种访问模式也可以抽象成一个类。