Problem Description
Explanation
To rotate the image by 90 degrees clockwise in-place, we can perform the rotation in layers starting from the outermost layer and moving towards the center. At each layer, we swap the elements in groups of four, rotating each element to its corresponding position in the 90-degree rotated image.
- We iterate through each layer starting from the outermost layer.
- For each layer, we iterate through the elements in that layer from left to right.
- For each element, we perform four swaps to rotate the elements in that layer.
Time complexity: O(n^2)
Space complexity: O(1)
Solutions
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int layer = 0; layer < n / 2; layer++) {
int first = layer;
int last = n - 1 - layer;
for (int i = first; i < last; i++) {
int offset = i - first;
int top = matrix[first][i];
matrix[first][i] = matrix[last - offset][first];
matrix[last - offset][first] = matrix[last][last - offset];
matrix[last][last - offset] = matrix[i][last];
matrix[i][last] = top;
}
}
}
}
Related LeetCode Problems
Loading editor...