Sunday, February 2, 2020

Rotate Matrix at 90 degree

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


Example :

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]]
int[][] rotateImage(int[][] a) {
}

Solution:

First of all let's think how we can achieve this.

There are two steps to solve this:

1. Transpose of Matrix
2. Mirror the column

Have you heard of transpose of Matrix ? Following diagram explains about transpose of Matrix :



In transpose of Matrix, the diagonal will remain same.

Following is the code for transpose of the Matrix:

*** [ here the j should start from i as we need to swap only one side of the diagonal and other will be automatically taken care ] ***


// int[][] a = input
int j = 0;
int i = 0;
for(i=0;i<a.length;i++){
    for(j=i;j<a.length;j++){
        int tmp = a[i][j];            
        a[i][j] = a[j][i];
        a[j][i] = tmp;
    }
} 

After doing transpose of the matrix following will be the output :

a = [[1, 4, 7],
     [2, 5, 8],
     [3, 6, 9]]
But required output is this :

rotateImage(a) =
    [[7, 4, 1],
     [8, 5, 2],
     [9, 6, 3]]
So we need to swap the columns:

*** [We need to swap only half of the columns and other will automatically fixed.] ***

Following is the code for swapping the column :



int N = a.length-1;
for(j=0;j<a.length/2;j++){
    for(i =0;i<a.length;i++){
        int tmp = a[i][j];
        a[i][j] = a[i][N-j];
        a[i][N-j] = tmp;
        System.out.println(a[i][j]);
    }
}

so, by combining above two steps following is the complete solution:


Solution:


int[][] rotateImage(int[][] a) {
    // int[][] a = input
    int j = 0;
    int i = 0;
    for(i=0;i<a.length;i++){
        for(j=i;j<a.length;j++){
            int tmp = a[i][j];            
            a[i][j] = a[j][i];
            a[j][i] = tmp;
        }
    } 
    int N = a.length-1;
    for(j=0;j<a.length/2;j++){
        for(i =0;i<a.length;i++){
            int tmp = a[i][j];
            a[i][j] = a[i][N-j];
            a[i][N-j] = tmp;
            System.out.println(a[i][j]);
        }
    }
    return a;
}


No comments:

Post a Comment

Rotate Matrix at 90 degree

You are given an n x n 2D matrix that represents an image. Rotate the image by 90 degrees (clockwise). Example : For a = [[1, 2, 3],...