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.
matrix.length == n
matrix[i].length == n
1 <= n <= 20
-1000 <= matrix[i][j] <= 1000
n x n
.n
?
n
ranges from 1 to 20.To achieve the in-place rotation of the matrix:
Here are the steps in detail:
matrix[i][j]
with matrix[j][i]
for each element in the upper triangle of the matrix (i.e., where i < j
).Given matrix:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Transpose the matrix:
[
[1, 4, 7],
[2, 5, 8],
[3, 6, 9]
]
Reverse each row:
[
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
#include <vector>
#include <algorithm>
void rotate(std::vector<std::vector<int>>& matrix) {
int n = matrix.size();
// Transpose the matrix
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
std::swap(matrix[i][j], matrix[j][i]);
}
}
// Reverse each row
for (int i = 0; i < n; ++i) {
std::reverse(matrix[i].begin(), matrix[i].end());
}
}
Thus, the overall time complexity is O(n^2).
Since we are performing the operation in-place and not allocating additional space for another matrix, the space complexity is O(1) (excluding the space required for the input matrix itself).
Feel free to ask if you have any questions or need further clarification.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?