Matrix Left Rotation

By   Tewodros   Date Posted: Feb. 22, 2022  Hits: 890   Category:  Algorithm   Total Comment: 0             A+ A-


side

Given a N X N matrix (2-D array) of integers, we want to rotate it 90 degrees to the left only one time as shown in the above image.

Solution:

We first transpose (switch first row second column with second row first column…) the array as shown in the image above (see the first two matrices) .

Then we revert the numbers in each row to get the final outcome.

public void Rotate(int[][] matrix) {     

        for(int i=0;i<matrix.Length; i++)    {

           for(int j=i;j<matrix[0].Length; j++)  {

               swap(ref matrix[i][j], ref matrix[j][i]);    

           }

       }

       for(int i=0;i<matrix.Length; i++)  {

           int m = matrix[0].Length;

           for(int j=0;j<matrix[0].Length/2; j++)        {

               swap(ref matrix[i][j], ref matrix[i][m-j-1]);                

           }

       }     

   }

   

   void swap(ref int i, ref int j)  {

       int temp = i;

       i = j;

       j = temp;

   }


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* thrcot

Back to Top