Introduction
Rotating a matrix by 180 degrees is a multi-dimensional array problem. It had been asked in the NVIDIA interview round for the role of software engineers/developers. Alongside it is one of those problems that checks an individual's critical thinking by analyzing the most fundamental approach of the programmer.
In this article, we’ll use two methods to solve this problem; the first is the brute force or naive approach, and the second is by swapping positions.
Problem Statement
Given a square matrix, the task is to turn it 180 degrees without using extra space.
Sample Examples
Example 1:
Input:
Output:
Example 2:
Input:
Output:
Must Read, Array Implementation of Queue and Rabin Karp Algorithm
Naive Approach (Rotated Matrix)
A brute force solution to this problem could be by printing a rotated matrix.
In this approach, we’ll simply print the reverse of the matrix.
Given Matrix =
First we are rotating it by 90 degrees, the new matrix will be:
90 Degrees Rotated Matrix =
When we rotate it again by 90 degrees then the matrix will become:
180 Degrees Rotated Matrix =
Algorithm
- In order to rotate a matrix, take the matrix as an input.
- Traverse the whole matrix to the end.
- Now start printing the matrix from the last cell to the first cell.
- End
Implementation in C++
#include <bits/stdc++.h>
#include<iostream>
#define N 3
using namespace std;
// Function in order to Rotate the matrix by 180 degree
void rotate(int matrix[][N])
{
//Now print from the last cell to first cell of the matrix
for (int i = N - 1; i >= 0; i--)
{
for (int j = N - 1; j >= 0; j--)
cout<< matrix[i][j]<<" ";
cout<<"\n";
}
}
// Main function of the program
int main()
{
int matrix[N][N] =
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
rotate(matrix);
return 0;
}
Output :
Time complexity
The time complexity of this approach is O(N*N) as we are traversing the whole matrix and printing the matrix again in the reverse order in the same loop.
Space complexity
The space complexity of this approach is O(1), as we are using constant extra space.