Rotate M*N Matrix


The simplest way is to create another matrix, which has the dimensions N * M (if the original has M * N) and then use nested loops to copy values from one matrix to another… Just mind the correct index usage.

static int[,] RotateMatrix(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;
}

So a basic sample would look like:

class RotateMaxtrixConsole
    {
        static void Main(string[] args)
        {
            int[,] matrix2D = new int[,] 
            { 
                { 12 }, 
                { 34 }, 
                { 56 }, 
                { 78 }
            };
 
            Console.WriteLine("original matrix content:");
            DisplayMatrix(matrix2D);
 
            int[,] rotatedMatrix = RotateMatrix(matrix2D);
 
            Console.WriteLine("rotated matrix content:");
            DisplayMatrix(rotatedMatrix);
 
            Console.WriteLine("press <AnyKey> to exit.");
            Console.ReadKey();
        }
 
 
        static int[,] RotateMatrix(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;
        }
 
        static void DisplayMatrix(int[,] theMatrix)
        {
            for (int curRow = 0; curRow < theMatrix.GetLength(0); curRow++)
            {
                for (int curColumn = 0; curColumn < theMatrix.GetLength(1); curColumn++)
                {
                    Console.Write(theMatrix[curRow, curColumn] + " ");
                }
                Console.WriteLine();
            }
            Console.WriteLine();
        }
    }