Skip to content

Example: Rotate image

Roberto Fronteddu edited this page Jul 30, 2024 · 3 revisions

To rotate an 𝑛×𝑛 2D matrix (image) by 90 degrees clockwise in place, you can follow these steps:

  • Transpose the matrix: Convert all rows to columns (swap elements at matrix[i][j] with matrix[j][i]).
  • Reverse each row: Reverse the elements in each row to achieve the 90-degree rotation.
public class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;

        // Transpose the matrix
        for (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 row
        for (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;
            }
        }
    }
}

Clone this wiki locally