Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Matrix rotation
//Title of this code #include <iostream> using namespace std; const int n = 4; const int m = 4; /* Rotate by +90: Transpose Reverse each row Rotate by -90: Transpose Reverse each column Rotate by +180: Method 1: Rotate by +90 twice Method 2: Reverse each row and then reverse each column Rotate by -180: Method 1: Rotate by -90 twice Method 2: Reverse each column and then reverse each row Method 3: Reverse by +180 as they are same */ void rotateMatrix2(int t[n][m]) { // transpose for (int i = 0; i < n; ++i) for (int j = i + 1; j < m; ++j) swap(t[i][j], t[j][i]); // reverse the rows for (int i = 0; i < n; ++i) for (int j = 0; j < m / 2; ++j) swap(t[i][j], t[i][m - j - 1]); } void rotateMatrix(int t[n][m]) { int dest[n][m]; // transpose and reverse but need another matrix for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) dest[j][n - i - 1] = t[i][j]; // copy the matrix for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) t[i][j] = dest[i][j]; } void printMatrix(int t[n][m]) { for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cout << t[i][j] << " "; } cout << endl; } } int main() { int dest[n][m]; int t[n][m] = { {5, 1, 2, 6}, {1, 1, 9, 3}, {1, 1, 2, 3}, {8, 1, 2, 7} }; printMatrix(t); rotateMatrix2(t); //rotateMatrix(t); //rotateMatrix2(t); //rotateMatrix(t); cout << endl; printMatrix(t); }
run
|
edit
|
history
|
help
0
CountingSort
new
Test1
test111
PrintShapePointer
abraham
Reverse a string
floyd alfa 1
hh
3SUM problem