Rotate Four Cells at a Time
Intuition
Process the matrix layer by layer from the outside in. For each layer, rotate groups of four elements that form a cycle. The element at position (i, j) moves to (j, n-1-i), which moves to (n-1-i, n-1-j), which moves to (n-1-j, i), which moves back to (i, j). By rotating these four positions simultaneously using a temporary variable, we perform the rotation in place without needing extra space.
Algorithm
- For each layer from 0 to n/2 - 1 (outer loop variable i):
- For each position in the current layer from i to n-1-i-1 (inner loop variable j):
- Save matrix[i][j] in a temp variable.
- Move the left element to the top: matrix[i][j] = matrix[n-1-j][i].
- Move the bottom element to the left: matrix[n-1-j][i] = matrix[n-1-i][n-1-j].
- Move the right element to the bottom: matrix[n-1-i][n-1-j] = matrix[j][n-1-i].
- Move temp to the right: matrix[j][n-1-i] = temp.
O(n^2)SpaceO(1)Code (C++ · Java · Python · Go)
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - 1 - i; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[n - 1 - j][i];
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j];
matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];
matrix[j][n - 1 - i] = temp;
}
}
}
};class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - 1 - i; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[n - 1 - j][i];
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j];
matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];
matrix[j][n - 1 - i] = temp;
}
}
}
}def rotate(matrix: list[list[int]]) -> None:
n = len(matrix)
for i in range(n // 2):
for j in range(i, n - 1 - i):
temp = matrix[i][j]
matrix[i][j] = matrix[n - 1 - j][i]
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j]
matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i]
matrix[j][n - 1 - i] = tempfunc rotate(matrix [][]int) {
n := len(matrix)
for i := 0; i < n/2; i++ {
for j := i; j < n-1-i; j++ {
temp := matrix[i][j]
matrix[i][j] = matrix[n-1-j][i]
matrix[n-1-j][i] = matrix[n-1-i][n-1-j]
matrix[n-1-i][n-1-j] = matrix[j][n-1-i]
matrix[j][n-1-i] = temp
}
}
}