Rotate Image - The Coding Shala

Home >> Interview Questions >> Rotate Image

 In this post, we will learn how to Rotate an Image or in other words how to Rotate a Matrix. We will implement Rotate Image Java Solution.

Rotate Image Problem

You are given an n x n 2D matrix that represents an image. Rotate the image by 90 degrees (clockwise).

Example 1:
For a = [[1, 2, 3],
             [4, 5, 6],
             [7, 8, 9]]
the output should be 
rotateImage(a) =
           [[7, 4, 1],
           [8, 5, 2],
           [9, 6, 3]]

Rotate Image Java Solution

Approach 1

Using extra space. We can do this easily by using extra matrix.

Java Program: 

int[][] rotateImage(int[][] a) {
    int len = a.length;
    int[][] ans = new int[len][len];
    for(int i=0;i<len;i++){
        for(int j=0;j<len;j++){
            ans[j][len-i-1] = a[i][j];
        }
    }
    return ans;
}

Approach 2

Without using extra space.

Here is a common method to solve image rotation problems.

For clockwise rotation

Step 1: First we reverse up to down array rows that means the first row becomes the last row and the second row becomes the second the last row and so on.

Step 2: Swap the elements in the symmetry.

Example:

1 2 3        7 8 9       7 4 1
4 5 6  => 4 5 6  => 8 5 2
7 8 9       1 2 3        9 6 3

For AntiClockwise rotation

Step 1: First we reverse the array left to right that means first column become last column and second column become secont last column and so on.

Step 2: Swap the elements in the symmetry.

Example:

1 2 3        3 2 1       3 6 9
4 5 6  => 6 5 4  => 2 5 8
7 8 9        9 8 7       1 4 7

Java Program for Clockwise Image Rotation: 

class Solution {
    public void rotate(int[][] matrix) {
        int row = matrix.length;
        int col = matrix[0].length;
        for(int i=0;i<row/2;i++){
            for(int j=0;j<col;j++){
                int tmp = matrix[i][j];
                matrix[i][j] = matrix[row-i-1][j];
                matrix[row-i-1][j] = tmp;
            }
        }
        for(int i=0;i<row;i++){
            for(int j=i+1;j<col;++j){
                int tmp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = tmp;
            }
        }
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

Anti Diagonals - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala

Java Method Overloading - The Coding Shala