48. Rotate Image
Intuition
Complexity
Space Complexity
Time Complexity
Code
public void rotate(int[][] matrix) {
int rowCount = matrix.length;
int colCount = matrix[0].length;
// Step 1: Transpose the matrix (flip over diagonal)
for (int row = 0; row < rowCount; ++row) {
for (int col = row; col < colCount; ++col) {
// Swap matrix[row][col] with matrix[col][row]
int temp = matrix[row][col];
matrix[row][col] = matrix[col][row];
matrix[col][row] = temp;
}
}
// Step 2: Reverse each row (mirror horizontally)
int left = 0;
int right = colCount - 1;
while (left < right) {
for (int row = 0; row < rowCount; ++row) {
// Swap elements at the current row between left and right columns
int temp = matrix[row][left];
matrix[row][left] = matrix[row][right];
matrix[row][right] = temp;
}
left++;
right--;
}
}
Last updated