fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. class Rotatable_Image
  8. {
  9. private:
  10. static const int ROTATIONS_IN_CIRCLE = 4;
  11.  
  12. std::vector<std::vector<int>> matrix;
  13. int rotation_count = 0;
  14.  
  15. public:
  16. Rotatable_Image(size_t size)
  17. {
  18. matrix.resize(size, std::vector<int>(size));
  19. }
  20.  
  21. // rotates image 90 degrees clockwise
  22. void rotate()
  23. {
  24. ++rotation_count;
  25.  
  26. while (rotation_count > ROTATIONS_IN_CIRCLE)
  27. {
  28. rotation_count -= ROTATIONS_IN_CIRCLE;
  29. }
  30. }
  31.  
  32. int & get_pixel(int row, int column)
  33. {
  34. switch (rotation_count % ROTATIONS_IN_CIRCLE)
  35. {
  36. case 0:
  37. return matrix[row][column];
  38. case 1:
  39. return matrix[matrix.size() - column - 1][row];
  40. case 2:
  41. return matrix[matrix.size() - row - 1][matrix.size() - column - 1];
  42. case 3:
  43. return matrix[column][matrix.size() - row - 1];
  44. }
  45. }
  46.  
  47. size_t size()
  48. {
  49. return matrix.size();
  50. }
  51. };
  52.  
  53. int main()
  54. {
  55. const size_t SIZE = 7;
  56.  
  57. Rotatable_Image image(SIZE);
  58.  
  59. cout << "******* original image ******" << endl;
  60. int value = 0;
  61. for (size_t i = 0; i < image.size(); ++i)
  62. {
  63. for (size_t j = 0; j < image.size(); ++j)
  64. {
  65. cout << (image.get_pixel(i, j) = value++) << ' ';
  66. }
  67.  
  68. value++;
  69. cout << '\n';
  70. }
  71.  
  72. // rotate image 90 degree clockwise O(1)time & O(1)memory
  73. image.rotate();
  74.  
  75. cout << "\n******* rotated image ******" << endl;
  76. for (size_t i = 0; i < image.size(); ++i)
  77. {
  78. for (size_t j = 0; j < image.size(); ++j)
  79. {
  80. cout << image.get_pixel(i, j) << ' ';
  81. }
  82.  
  83. cout << '\n';
  84. }
  85. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
******* original image ******
0 1 2 3 4 5 6 
8 9 10 11 12 13 14 
16 17 18 19 20 21 22 
24 25 26 27 28 29 30 
32 33 34 35 36 37 38 
40 41 42 43 44 45 46 
48 49 50 51 52 53 54 

******* rotated image ******
48 40 32 24 16 8 0 
49 41 33 25 17 9 1 
50 42 34 26 18 10 2 
51 43 35 27 19 11 3 
52 44 36 28 20 12 4 
53 45 37 29 21 13 5 
54 46 38 30 22 14 6