You are given a n x n 2D matrix representing an image.
Rotate the image by degrees (clockwise).
Follow up:
Could do this in-place?
Reference Leetcode[array]: Spiral Matrix II's iterative approach, the first to complete the rotation of the outer ring, and then rotate the inner ring in turn. My C + + code is as follows:
void rotate (vector<vector<int> > &matrix) { int beginrow = 0, Endrow = matrix.size ()-1, Begincol = 0 , Endcol = Matrix[0].size ()-1; while (Beginrow <= endrow && begincol <= endcol) {for (int i = 0; i < Endcol-begincol; ++i) { int tmp = matrix[beginrow ][begincol + i]; Matrix[beginrow ][begincol + i] = matrix[ endrow-i][begincol ]; matrix[ endrow-i][begincol ] = matrix[ Endrow] [ endcol-i]; matrix[ Endrow] [ endcol-i] = matrix[beginrow + i][ endcol ]; Matrix[beginrow + i][ endcol ] = tmp; } ++beginrow; --endrow; ++begincol; --endcol;} }
See a more peculiar solution on the discuss, the idea is: first the matrix upside down, and then the upper left to the bottom right diagonal fold to complete the rotation, its C + + code implementation is very concise:
void rotate (vector<vector<int> > &matrix) { reverse (matrix.begin (), Matrix.end ()); for (unsigned i = 0; i < matrix.size (), ++i) for (unsigned j = i+1; J < Matrix[i].size (); ++j) swap (matrix[ I][J], matrix[j][i]);}
Leetcode[array]: Rotate Image