Rotate Matrix

1.7 Rotate Matrix: Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?

#include <iostream>
#include <string>

using namespace std;


void printMatrix(size_t N, int (*matrix)[3]) {
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    cout << endl;
}

// not in place
// O(?) space
// O(N) algorithm
void rotateMatrix(size_t N, int (*matrix)[3]) {
    printMatrix(3, matrix);
    int newMatrix[3][3];

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            // for each row in matrix add to last column new matrix
            newMatrix[j][N - i - 1] = matrix[i][j];
        }
    }

    printMatrix(3, newMatrix);
}



int main()
{
    /*
        1 2 3       7 8 9    
        4 5 6  ->  8 5 2
        7 8 9      9 6 3
    */
    int matrix[3][3] = {
        {1,2,3},
        {4,5,6},
        {7,8,9}
    };

    rotateMatrix(3, matrix);

}

Last updated