Advertisement
RaFiN_

rotate matrix without using any extra space

Dec 20th, 2019
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. /*
  2.  * clockwise rotate
  3.  * first reverse up to down, then swap the symmetry
  4.  * 1 2 3     7 8 9     7 4 1
  5.  * 4 5 6  => 4 5 6  => 8 5 2
  6.  * 7 8 9     1 2 3     9 6 3
  7. */
  8. void rotate(vector<vector<int> > &matrix) {
  9.     reverse(matrix.begin(), matrix.end());
  10.     for (int i = 0; i < matrix.size(); ++i) {
  11.         for (int j = i + 1; j < matrix[i].size(); ++j)
  12.             swap(matrix[i][j], matrix[j][i]);
  13.     }
  14. }
  15.  
  16. /*
  17.  * anticlockwise rotate
  18.  * first reverse left to right, then swap the symmetry
  19.  * 1 2 3     3 2 1     3 6 9
  20.  * 4 5 6  => 6 5 4  => 2 5 8
  21.  * 7 8 9     9 8 7     1 4 7
  22. */
  23. void anti_rotate(vector<vector<int> > &matrix) {
  24.     for (auto vi : matrix) reverse(vi.begin(), vi.end());
  25.     for (int i = 0; i < matrix.size(); ++i) {
  26.         for (int j = i + 1; j < matrix[i].size(); ++j)
  27.             swap(matrix[i][j], matrix[j][i]);
  28.     }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement