> For the complete documentation index, see [llms.txt](https://maksimdan.gitbook.io/interview-practice-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://maksimdan.gitbook.io/interview-practice-problems/coding_practice_questions/interview_questions1/rotate-matrix.md).

# 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?

```cpp
#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);

}
```
