• Source
    1. /* package whatever; // don't place package name! */
    2.  
    3. import java.util.*;
    4. import java.lang.*;
    5. import java.io.*;
    6.  
    7. /**
    8.  * How do you rotate a two dimensional array?
    9.  *
    10.  * Refer : http://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array
    11.  */
    12. class Ideone {
    13. public static void main(String[] args){
    14. int[][] a = {
    15. {1, 2, 3, 4 },
    16. {5, 6, 7, 8 },
    17. {9, 10, 11, 12},
    18. {13, 14, 15, 16}
    19. };
    20.  
    21. printMatrix("Before rotation :", a);
    22.  
    23. int m = a.length;
    24. int n = a[0].length;
    25. int[][] dest = new int[m][n];
    26.  
    27. for(int r=0; r<m; r++){
    28. for(int c=0; c<n; c++){
    29. dest[c][m-r-1] = a[r][c];
    30. }
    31. }
    32. printMatrix("After rotation :", dest);
    33. }
    34.  
    35. private static void printMatrix(String str, int[][] a){
    36. System.out.println(str);
    37.  
    38. for(int i=0; i<a.length; i++){
    39. for(int j=0; j<a[0].length; j++){
    40. System.out.print(" "+a[i][j]+ " ");
    41. }
    42. System.out.println();
    43. }
    44. }
    45. }
    46.