LeetCode [Array]: Rotate Image
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?
Refer to the LeetCode [Array]: Spiral Matrix II iteration idea. First, complete the rotation of the outermost ring, and then rotate the inner ring in sequence. My C ++ code is as follows:
void rotate(vector
> &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; }}
The idea of seeing a strange solution on Discuss is: first put the matrix upside down, and then rotate along the diagonal line between the top left and the bottom right, its C ++ code implementation is very concise:
void rotate(vector
> &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]);}