Matrix: Given a matrix, rotate matrix 180 degree

Problem Statement:

Given a matrix, rotate matrix 180 degree

Example:

Input:  

matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

Output: 

[[9, 8, 7],
 [6, 5, 4],
 [3, 2, 1]]

Solution 1: Swapping approach

We can perform inplace swapping.

For a matrix as below:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Swap the first row and the last row and reverse

[9, 8, 7]
[4, 5, 6]
[3, 2, 1]

Then reverse the middle row

[9, 8, 7]
[6, 5, 4]
[3, 2, 1]

Time Complexity: O(n^2)
Space Complexity: O(1)

Code Solution

#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include <numeric>

using namespace std;


void solution(vector<vector<int>> &mat)
{
    int N = mat.size();
 
    if (N == 0) 
    {
        return;
    }
 
    for (int i = 0; i < N / 2; i++)
    {
        for (int j = 0; j < N; j++) 
        {
            swap(mat[i][j], mat[N - i - 1][N - j - 1]);
        }
    }
 
    if (N % 2 != 0)
    {
        for (int j = 0; j < N/2; j++) 
        {
            swap(mat[N/2][j], mat[N/2][N - j - 1]);
        }
    }
}


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

    for (int i = 0; i < mat.size(); i++) 
    {
        for (int j = 0; j < mat[i].size(); j++) 
        {
            cout << mat[i][j] << " ";
        }
        cout << "\n";
    }

    return 0;
}

Output

9 8 7 
6 5 4 
3 2 1
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *