Mar 8, 2022

Rotate matrix in place

 #include <iostream>

using namespace std;


void printMatrix(int a[4][4])

{

    for(int i=0;i<4;i++)

    {

        for(int j=0;j<4;j++)

        {

            cout << a[i][j] << " ";

        }

        cout << endl;

    }

}

void rotateMatrixInPlace(int a[4][4])

{

    cout << "before rotation\n";

    printMatrix(a);

    

// Transpose 

    for(int i=0;i<4; i++)

    {

        for(int j=i+1;j<4;j++)

        {

            int t = a[i][j];

            a[i][j] = a[j][i];

            a[j][i] = t;

        }

        

    }


// Mirror    

    for(int i=0;i<4; i++)

    {

        for(int j=0;j<2;j++)

        {

            int t = a[i][j];

            a[i][j] = a[i][3-j];

            a[i][3-j] = t;

        }

    }

    

    cout << "after rotation\n";

    printMatrix(a);

}

int main() {

// your code goes here

int a[4][4] = 

{

    1, 2, 3, 4,

    5, 6, 7, 8,

    9, 0, 1, 2,

    3, 4, 5, 6

};

rotateMatrixInPlace(a);

return 0;

}


No comments: