You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise ).
Follow up:
Cocould you do this in-place?
The original image rotates 90 degrees clockwise. Because the space complexity is a constant, iteration rotation should be performed.
Class Solution {public: void rotate (vector
> & Matrix) {int n = matrix. size (); int layers = n/2; // Number of circles in the image rotation for (int layer = 0; layer <layers; layer ++) // layer of each loop, right cyan to purple for (int I = layer; I
The following is another solution provided by netizens:
Class Solution {public: void rotate (vector
> & Matrix) {int I, j, temp; int n = matrix. size (); // reverse the for (int I = 0; I <n; ++ I) {for (int j = 0; j <n-I; ++ j) {temp = matrix [I] [j]; matrix [I] [j] = matrix [n-1-j] [n-1-I]; matrix [n-1-j] [n-1-I] = temp ;}// reverse along the horizontal midline for (int I = 0; I <n/2; ++ I) {for (int j = 0; j <n; ++ j) {temp = matrix [I] [j]; matrix [I] [j] = matrix [n-1-I] [j]; matrix [n-1-I] [j] = temp ;}}}};