Matrices
Rotate Image
DESCRIPTION (inspired by Leetcode.com)
Write a function to rotate an n x n 2D matrix representing an image by 90 degrees clockwise. The rotation must be done in-place, meaning you should modify the input matrix directly without using an additional matrix for the operation.
Input:
matrix = [ [1,4,7], [2,5,8], [3,6,9] ]
Output:
[ [3,2,1], [6,5,4], [9,8,7] ]
Explanation: The matrix is rotated by 90 degrees clockwise, transforming its columns into rows in reverse order.
public class Solution {
public void rotate_image(int[][] matrix) {
// Your code goes here
}
}Run your code to see results here
Have suggestions or found something wrong?
Explanation
This problem can be done in two steps. We first transpose the matrix, then reverse the elements in each row.
Step 1:
Transpose the matrix by swapping the elements across the diagonal. This can be done in-place by using a nested for loop to swap the elements.
public void rotate(int[][] matrix) {int n = matrix.length;// Transpose the matrixfor (int i = 0; i < n; i++) {for (int j = i; j < n; j++) {int temp = matrix[i][j];matrix[i][j] = matrix[j][i];matrix[j][i] = temp;}}// Reverse each rowfor (int i = 0; i < n; i++) {for (int j = 0; j < n / 2; j++) {int temp = matrix[i][j];matrix[i][j] = matrix[i][n - 1 - j];matrix[i][n - 1 - j] = temp;}}}
n = 3
0 / 12
Step 2:
Reverse the elements in each row of the matrix.
public void rotate(int[][] matrix) {int n = matrix.length;// Transpose the matrixfor (int i = 0; i < n; i++) {for (int j = i; j < n; j++) {int temp = matrix[i][j];matrix[i][j] = matrix[j][i];matrix[j][i] = temp;}}// Reverse each rowfor (int i = 0; i < n; i++) {for (int j = 0; j < n / 2; j++) {int temp = matrix[i][j];matrix[i][j] = matrix[i][n - 1 - j];matrix[i][n - 1 - j] = temp;}}}
swap matrix[2][2] and matrix[2][2]
0 / 4
Solution
public void rotate(int[][] matrix) {int n = matrix.length;// Transpose the matrixfor (int i = 0; i < n; i++) {for (int j = i; j < n; j++) {int temp = matrix[i][j];matrix[i][j] = matrix[j][i];matrix[j][i] = temp;}}// Reverse each rowfor (int i = 0; i < n; i++) {for (int j = 0; j < n / 2; j++) {int temp = matrix[i][j];matrix[i][j] = matrix[i][n - 1 - j];matrix[i][n - 1 - j] = temp;}}}
rotate image
0 / 17
What is the time complexity of this solution?
O(2ⁿ)
O(4ⁿ)
O(n²)
O(n log n)