48 Rotate Image
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?
Solution
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int m = matrix.size();
if ( m == 0 ) return;
int n = matrix[0].size();
if ( n == 0 ) return;
for ( int i = 0; i < m-1; i++ ) {
for ( int j = i; j < n-i-1; j++ ) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[m-j-1][i];
matrix[m-j-1][i] = matrix[m-i-1][n-j-1];
matrix[m-i-1][n-j-1] = matrix[j][n-i-1];
matrix[j][n-i-1] = tmp;
}
}
return;
}
};
Notes
Made mistake in my first try. (Note the left and right bound of i and j for looping.)