You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
Do not think too much about this problem, don't be scared by the "Matrix" word. This problem can be done in an easy way.
like the picture below:
origin:rotate:
you can read as the 1st picture, and put it on a new one with a different order.
1 class Solution { 2 public: 3 void rotate(vector<vector<int> > &matrix) { 4 auto result = matrix; 5 for (int j=0; j<matrix.size(); j++){ 6 for (int i=0; i<matrix.size(); i++){ 7 result[j][matrix.size()-i-1] = matrix[i][j]; 8 } 9 } 10 matrix = result; 11 } 12 };
this is a naive one, it take extra space to rotate, there are some smarter way which can do in-place transposition. I'll check that later.