Rotate Matrix II - C++ Solution

1. Introduction

The "Rotate Matrix II" problem extends the concept of matrix rotation by requiring a 180-degree rotation in a clockwise direction. This task involves flipping the matrix elements in an N × N array, where in-place manipulation is crucial for maintaining space efficiency.

Problem

Given an N × N integer matrix, the objective is to rotate the matrix by 180 degrees in a clockwise direction. This rotation should be executed in-place to optimize space usage and in quadratic time, suitable for the size of the matrix.

2. Solution Steps

1. Rotate the matrix by 180 degrees by reversing each row and then reversing each column.

2. This can be done in two steps: First, reverse the order of the rows. Second, reverse the order of the elements in each row.

3. These steps can be achieved using standard array manipulation techniques without needing additional storage.

3. Code Program

#include <iostream>
#include <vector>
using namespace std;

// Function to rotate the matrix by 180 degrees clockwise
void rotateMatrix180(vector<vector<int>>& matrix) {
    int n = matrix.size();

    // Reverse the order of the rows
    for (int i = 0; i < n / 2; i++) {
        for (int j = 0; j < n; j++) {
            swap(matrix[i][j], matrix[n - 1 - i][n - 1 - j]);
        }
    }

    // If n is odd, reverse the middle row
    if (n % 2 != 0) {
        for (int j = 0; j < n / 2; j++) {
            swap(matrix[n / 2][j], matrix[n / 2][n - 1 - j]);
        }
    }
}

int main() {
    vector<vector<int>> matrix = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
        {13, 14, 15, 16}
    };

    rotateMatrix180(matrix);

    // Print the rotated matrix
    for (const auto& row : matrix) {
        for (int val : row) {
            cout << val << " ";
        }
        cout << endl;
    }
    return 0;
}

Output:

16 15 14 13

Explanation:

The program achieves a 180-degree rotation by first reversing the order of the rows and then reversing each element in each row. 

This approach ensures that each element is effectively rotated by 180 degrees while maintaining the matrix's in-place integrity. The implementation is efficient, with quadratic time complexity, making it suitable for large N × N matrices.


Comments