How to rotate a matrix of size n*n to 90 degree using C#?

CsharpServer Side ProgrammingProgramming

In a Matrix, there is a total of n/2 squares in n*n matrix and we can process each square one at a time using nested loop. In each square elements are moving in a cycle of 4 elements. we swap the elements involved in an anticlockwise direction for each cycle

Element at position (n-1-j,i) will go to position(i,j)

Element at position (i,j) will go to position(j,n-1-i)

Element at position (j,n-1-i) will go to position(n-1-i,n-1-j)

Element at position (n-1-i,n-1-j) will go to position(n-1-j,i)

Example

 Live Demo

using System;
using System.Text;
namespace ConsoleApplication{
   public class Matrix{
      public void RotateMatrixBy90Degree(int[,] matrix){
         int n = matrix.GetLength(0);
         for (int i = 0; i < n / 2; i++){
            for (int j = i; j < n - i - 1; j++){
               int top = matrix[i, j];
               //MOve left to top
               matrix[i, j] = matrix[n - 1 - j, i];

               //Move bottom to left
               matrix[n - 1 - j, i] = matrix[n - i - 1, n - 1 - j];

               //Move right to bottom
               matrix[n - i - 1, n - 1 - j] = matrix[j, n - i - 1];

               //Move top to right
               matrix[j, n - i - 1] = top;
            }
         }
         for (int i = 0; i < n; i++){
            StringBuilder s = new StringBuilder();
            for (int j = 0; j < n; j++){
               s.Append(matrix[i, j] + " ");
            }
            Console.WriteLine(s);
            s = null;
         }
      }
   }
   class Program{
      static void Main(string[] args){
         Matrix m = new Matrix();
         int[,] matrix = { { 5, 1, 9, 11 }, { 2, 4, 8, 10 }, { 13, 3, 6, 7 }, { 15, 14, 12, 16 } };
         m.RotateMatrixBy90Degree(matrix);
      }
   }
}

Output

15 13 2 5
14  3 4 1
12  6 8 9
16 7 10 11
raja
Published on 27-Aug-2021 12:59:22
Advertisements