darrellp

Matrix rotation problem

Nov 16th, 2021 (edited)
781
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. //Determine Whether Matrix can Be Obtained By rotation
  2.  
  3. #include <iostream>
  4. #include <vector>
  5. #include <iomanip>
  6. using namespace std;
  7.  
  8. void Rotate(vector<vector<int>>& mat)
  9. {
  10.     int n = mat.size();
  11.     for (int i = 0; i < n; i++)
  12.     {
  13.         reverse(mat[i].begin(), mat[i].end());
  14.     }
  15.     for (int i = 0; i < n; i++) {
  16.         for (int j = i + 1; j < n; j++) {
  17.             swap(mat[i][j], mat[j][i]);
  18.         }
  19.     }
  20.  }
  21.  
  22. bool equals(vector<vector<int>>& mat, vector<vector<int>>& target) {
  23.     int n = mat.size();
  24.     for (int i = 0; i < n; i++) {
  25.         for (int j = 0; j < n; j++) {
  26.             if (mat[i][j] != target[i][j]) return false;
  27.         }
  28.     }
  29.     return true;
  30. }
  31. bool findRotation(vector<vector<int>>& mat, vector<vector<int>>& target)
  32. {
  33.     if (equals(mat, target)) return true;
  34.     Rotate(mat);
  35.     if (equals(mat, target)) return true;
  36.     Rotate(mat);
  37.     if (equals(mat, target)) return true;
  38.     Rotate(mat);
  39.     if (equals(mat, target)) return true;
  40.     return false;
  41.  
  42. }
  43.  
  44. void printMatrix(vector<vector<int>>& mat)
  45. {
  46.     int size = mat.size();
  47.  
  48.     for (int iRow = 0; iRow < size; iRow++)
  49.     {
  50.         for (int iCol = 0; iCol < size; iCol++)
  51.         {
  52.             cout << setw(3) << mat[iRow][iCol];
  53.         }
  54.         cout << endl;
  55.     }
  56. }
  57.  
  58. int main()
  59. {
  60.     vector<vector<int>> testRotMatrix = {
  61.         {0, 1, 2, 3},
  62.         {4, 5, 6, 7},
  63.         {8, 9, 10, 11},
  64.         {12, 13, 14, 15},
  65.     };
  66.     printMatrix(testRotMatrix);
  67.     cout << endl;
  68.     Rotate(testRotMatrix);
  69.     printMatrix(testRotMatrix);
  70.     cout << endl;
  71.  
  72.     vector<vector<int>> mat = { {0,1},{1,2} };
  73.     vector<vector<int>> target1 = { {1,0},{0,2} };
  74.     vector<vector<int>> target2 = { {1, 0}, {2, 1} };
  75.  
  76.     cout << (findRotation(mat, target1) ? "true" : "false") << endl;
  77.     cout << (findRotation(mat, target2) ? "true" : "false") << endl;
  78. }
  79.  
Add Comment
Please, Sign In to add comment