Today we have to write a program for rotating a given matrix by 90 degree. This code only works with square matrix.

Code

        public static void MatrixRotation<T>(T[,] matrix)
        {
            Console.WriteLine("\n Input Matrix");
            Print2DMatrix(matrix);
            int row = matrix.GetLength(0);
            int column = matrix.GetLength(1);

            T temp;
            for (int i = 0; i < row; i++)
            {
                for (int j = i + 1; j < column; j++)
                {
                    temp = matrix[j, i];
                    matrix[j, i] = matrix[i, j];
                    matrix[i, j] = temp;
                }
            }


            for (int i = 0; i < row / 2; i++)
            {
                for (int j = 0; j < column; j++)
                {
                    temp = matrix[j, i];
                    matrix[j, i] = matrix[j, row - i - 1];
                    matrix[j, row - i - 1] = temp;
                }
            }
            Console.WriteLine("\n Rotation matrix");
            Print2DMatrix(matrix);

        }

        private static void Print2DMatrix<T>(T[,] matrix)
        {
            Console.WriteLine("--------------\n");
            int row = matrix.GetLength(0);
            int column = matrix.GetLength(1);

            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < column; j++)
                {
                    Console.Write(matrix[i, j] + " ");
                }
                Console.WriteLine(" ");
            }

        }

Result


Input Matrix

————–

11 12 13 14 15

21 22 23 24 25

31 32 33 34 35

41 42 43 44 45

51 52 53 54 55

Rotation matrix

————–

51 41 31 21 11

52 42 32 22 12

53 43 33 23 13

54 44 34 24 14

55 45 35 25 15

Input Matrix

————–

A B C D

E F G H

I J K L

M N O P

Rotation matrix

————–

M I E A

N J F B

O K G C

P L H D