Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Matrix rotation 90' anti-clock direction #2088

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions 2D_Array/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ Due to the fact that the elements of 2D arrays can be random accessed. Similar t
* Multiplication of two Matrices ----> [Java](/Code/Java/matrixop_mul.java)
* Overall Median of Matrix ---> [Java](/Code/Java/overall_median_matrix.java)
* Row-wise sum ----> [C++](/Code/C++/row_wise_sum.cpp) | [java](/Code/java/RowWise_Sum.java)
* Rotate Matrix 90' Anti-Clockwise without extra space ----> [C++](/Code/C++/RotateMatrixBy90.cpp)
* Spiral Print ----> [C++](/Code/C++/spiral_print.cpp)
* Staircase Search ----> [C++](/Code/C++/staircase_search.cpp)
* Substraction of two Matrices ----> [Java](/Code/Java/matrixop_sub.java)
Expand Down
83 changes: 83 additions & 0 deletions Code/C++/RotateMatrixBy90.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
#include<iostream> // for `i/o operation`
#define N 3 // defining size `N`

/*
function to swap values of two valiables
*/
void swap(int &num1, int &num2){
int temp = num1;
num1 = num2;
num2 = temp;
}

/*
function to print the matrix in matrix form
*/
void printMatrix(int matrix[N][N]){
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
std::cout<< "["<< matrix[i][j]<< "]\t";
}
std::cout<< std::endl;
}
}

/*
main function or the driver function
*/
int main(){
/* ###Test Case: 01
Matrix:
1 2 3
4 5 6
7 8 9
After Rotation:
3 6 9
2 5 6
7 8 9
*/
/* ###Test Case: 02
Matrix:
10 9 4
3 4 20
50 12 19
After Rotation:
4 20 19
9 4 12
10 3 50
*/

// Initializing matrix
int matrix[N][N] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
std::cout<< "\nInitial Matrix Is: "<< std::endl;
printMatrix(matrix);

for(int i = 0; i < N; i++){
for(int j = i; j < N; j++){
swap(matrix[i][j], matrix[j][i]);
}
}
// std::cout<< "\nTranspose Of Matrix Is: "<< std::endl;
// printMatrix(matrix);

for(int i = 0; i < N; i++){
int start = 0, end = N-1;

while(start < end){
swap(matrix[start][i], matrix[end][i]);
start += 1;
end -= 1;
}
}
std::cout<< "\n90` Rotation Of Matrix Is: "<< std::endl;
printMatrix(matrix);

return 0;
}

// Time Complexity: O(N*N), Where 'N' is the size of square matrix
// Auxiliary Space: O(1), No extra space has been used