Skip to main content

Rotate Image

Problem

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Solution Approach

Click - to see solution code
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
for (int i = 0; i < n / 2; i++) {
for (int j = 0; j < n - 2 * i - 1; j++) {
swap(matrix[i][i + j], matrix[n - i - 1 - j][i]);
swap(matrix[n - i - 1 - j][i],
matrix[n - i - 1][n - i - 1 - j]);
swap(matrix[n - i - 1][n - i - 1 - j],
matrix[i + j][n - i - 1]);
}
}
}
};