how to rotate a matrix 90 degrees clockwise

To rotate a matrix 90 degrees clockwise in C++, you can follow the steps below:

  1. Transpose the Matrix: Start by transposing the matrix, which involves swapping the elements across the main diagonal. The main diagonal is the line that starts from the top-left element and ends at the bottom-right element. This step is necessary to prepare the matrix for the rotation.

  2. Reverse Rows: After transposing the matrix, reverse each row of the transposed matrix. This step completes the rotation process.

Here is the code snippet that demonstrates the steps mentioned above:

#include <iostream>
#include <vector>

void rotateMatrixClockwise(std::vector<std::vector<int>>& matrix) {
    // Step 1: Transpose the matrix
    for (int i = 0; i < matrix.size(); i++) {
        for (int j = i + 1; j < matrix[i].size(); j++) {
            std::swap(matrix[i][j], matrix[j][i]);
        }
    }

    // Step 2: Reverse rows
    for (int i = 0; i < matrix.size(); i++) {
        int start = 0;
        int end = matrix[i].size() - 1;
        while (start < end) {
            std::swap(matrix[i][start], matrix[i][end]);
            start++;
            end--;
        }
    }
}

// Function to print the matrix
void printMatrix(const std::vector<std::vector<int>>& matrix) {
    for (const auto& row : matrix) {
        for (const auto& element : row) {
            std::cout << element << " ";
        }
        std::cout << std::endl;
    }
}

int main() {
    std::vector<std::vector<int>> matrix = {{1, 2, 3},
                                            {4, 5, 6},
                                            {7, 8, 9}};

    std::cout << "Original Matrix:" << std::endl;
    printMatrix(matrix);

    rotateMatrixClockwise(matrix);

    std::cout << "Matrix after 90 degrees clockwise rotation:" << std::endl;
    printMatrix(matrix);

    return 0;
}

This code snippet defines a function rotateMatrixClockwise that takes a 2D vector matrix as input and performs the rotation. The function first transposes the matrix and then reverses each row. The printMatrix function is used to print the original and rotated matrices for demonstration purposes.

When you run the code, you will see the original matrix followed by the matrix after the 90 degrees clockwise rotation.