diff --git a/2D_Array/readme.md b/2D_Array/readme.md index 74f031c3a..794be96dd 100644 --- a/2D_Array/readme.md +++ b/2D_Array/readme.md @@ -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) diff --git a/Code/C++/RotateMatrixBy90.cpp b/Code/C++/RotateMatrixBy90.cpp new file mode 100644 index 000000000..2fe84682c --- /dev/null +++ b/Code/C++/RotateMatrixBy90.cpp @@ -0,0 +1,83 @@ +#include // 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