How to rotate a matrix by 90 degree

0
This is the most asked question from matrix in the interviews . We will see how we can do this rotation in java  and C++ .


Input : { { 1 , 2 } , { 3 , 4 } }

Output : { { 2 , 4 } , { 1 , 3 } }


We have implemented the code in two languages , Java and C++

Java Code :


public class Matrix
{
    public static void rotate90(int[][] mat)
    {
        for(int i=0;i<mat.length;i++)
        {
            for(int j=i+1;j<mat[i].length;j++)
            {
                int temp = mat[i][j];
                mat[i][j] = mat[j][i];
                mat[j][i]= temp;
            }
        }
        
        for(int i=0;i<mat.length;i++)
        {
            int low=0;
            int highmat.length-1;
            while(low<high)
            {
                int temp = mat[low][i];
                mat[low][i] = mat[high][i];
                mat[high][i]= temp;
                low++;
                high--;
            }
        }
                
    }

    public static void main(String [] args)
    {
        int [][] mat = { {1,2,3},{3,4,5},{7,2,0}};

        rotate90(mat);
    }
}


C++ Code :


#include<iostream>

public class Matrix
{
    public static void rotate90(int[][] mat, int n)
    {
        for(int i=0;i<n;i++)
        {
            for(int j=i+1;j<n;j++)
            {
                int temp = mat[i][j];
                mat[i][j] = mat[j][i];
                mat[j][i]= temp;
            }
        }
        
        for(int i=0;i<n;i++)
        {
            int low=0;
            int highn-1;
            while(low<high)
            {
                int temp = mat[low][i];
                mat[low][i] = mat[high][i];
                mat[high][i]= temp;
                low++;
                high--;
            }
        }
                
    }
}

int main()
{
    int [][] mat = {{1,2},{3,4}};
    Matrix.rotate90(mat);
    return 0;
}
    





Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !