Rotate M*N Matrix (90 degrees)
If your matrix is represented by an array matrix[i, j]
, where the i
are the rows and the j
are the columns, then implement the following method:
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;
}
This works for matrices of all sizes.
Edit: If this operation is too expensive, then one could try changing the way one reads the matrix instead of changing the matrix itself. For example, if I am displaying the matrix as follows:
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();
}
then I could represent a 90-degree counterclockwise rotation by changing the way I read the matrix:
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();
}
This access pattern could be abstracted in a class, too.