Rotate Image - Java Solution

1. Introduction

This blog post addresses a common problem in image processing: rotating an image by 90 degrees clockwise. Specifically, we will discuss how to perform this rotation in-place on a square matrix, which represents an image.

Problem

Given an n x n 2D matrix that represents an image, we need to rotate the image 90 degrees clockwise. The key challenge is to perform this rotation in-place, meaning we have to modify the input matrix directly without allocating another 2D matrix for the rotation.

2. Solution Steps

1. Transpose the matrix: Swap matrix[i][j] with matrix[j][i].

2. Reverse each row of the matrix.

3. These two steps combined will effectively rotate the matrix by 90 degrees clockwise.

4. Ensure all modifications are done in-place.

3. Code Program

public class RotateImage {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        rotate(matrix);
        printMatrix(matrix); // Test the function and print the rotated matrix
    }

    // Function to rotate the matrix 90 degrees clockwise
    public static 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;
            }
        }
    }

    // Helper function to print the matrix
    private static void printMatrix(int[][] matrix) {
        for (int[] row : matrix) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }
}

Output:

7 4 1
8 5 2
9 6 3

Explanation:

1. rotate: This function rotates a given matrix by 90 degrees clockwise in-place.

2. It first transposes the matrix by swapping the elements matrix[i][j] and matrix[j][i].

3. Then, it reverses each row of the matrix, which results in a 90-degree clockwise rotation.

4. printMatrix: A helper function to print the matrix, demonstrating the rotation's result.

5. The process transforms the original matrix into its rotated form without using additional space for another matrix.


Comments