Matrix Rotation

We have to rotate the matrix by 90 degree anti-clockwise.

Input:


[  1  2   3   4   ] 

[  1  2   3   4   ] 
[  5  6   7   8   ] 
[  9  10  11  12  ] 
[  13 14  15  16  ]  

Output:


[  4  8   12  16  ] 
[  3  7   11  15  ] 
[  2  6   10  14  ] 
[  1  5   9   13  ] 

  

Java Program to do Matrix Rotation:



package com.sudharsan.examples;

public class MatrixRotation {

public static void main(final String... args) {
final Integer[][] a  = { { 1, 2, 3, 4},
                          { 5, 6, 7, 8},
                          { 9, 10, 11, 12},
                  { 13, 14, 15, 16}
};

System.out.print("Before Rotation : \n");
printMatrix(a);

int n = a[0].length;
for (int i = 0; i < n/2; i++) {
for (int j = i; j < n-1-i ; j++) {
int temp        = a[i][j];
a[i][j]         = a[j][n-1-i];
a[j][n-1-i]     = a[n-1-i][n-1-j];
a[n-1-i][n-1-j] = a[n-1-j][i];
a[n-1-j][i]     = temp;
}
System.out.println("\n");
printMatrix(a);
System.out.println("\n");
}
System.out.println("After rotation : \n");
printMatrix(a);
}
private static void printMatrix(Integer[][] a) {
for (int i = 0 ; i < a.length ; i++ ) {
System.out.print("[  ");
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + "  ");
}
System.out.print(" ] \n");
}
}
}

How it works:

  • In the 1st iteration, the elements in the outer side is rotated.
                 [  4  8   12  16  ] 
       [  3  6   7   15  ] 
       [  2  10  11  14  ] 
       [  1  5   9   13  ]          

  • In the 2nd iteration, the elements in the inner side is rotated.
                 [  4  8   12  16  ] 
       [  3  7   11  15  ] 
       [  2  6   10  14  ] 
       [  1  5   9   13  ]

Comments

Popular posts from this blog

Tiny URL Converter

Blocking Queue