Matrix Rotation in Java

In this article, we will explore a few different ways to rotate a matrix clock by 90 degrees.

Rotating Matrix to 90 Clockwise

Following is our Matrix. 

[    1        2        3    ]

[    4        5        6    ]

[    7        8        9    ]

We will explore multiple ways to rotate this matrix clockwise 90 

With Matrix Transpose

Matrix transpose is a flipped version of the matrix along its diagonal. In short, it is the same as interchanging the rows with columns. For the above matrix the transposed matrix will look like. 

[    1        4        7    ]

[    2        5        8    ]

[    3        6        9    ]

Also, the transposed matrix is equivalent to 90 Left rotation of the original array.
RoateMatrixWithTranspose
Here the Rotation of the matrix is done in two steps
1) We transpose the matrix 2) And we interchange the columns
public void rotateMatrixRight90Transpose(int[][] mat) {

    int m = mat.length;
    int n = mat[0].length;

    for (int i = 0; i < m; i++) {
      for (int j = i; j < n; j++) {
        int x = mat[i][j];
        mat[i][j] = mat[j][i];
        mat[j][i] = x;
        System.out.println("IC" + i + ":" + j);
      }
    }

    // swap cols
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n / 2; j++) {
        // swap mat[i][j] with mat[N-i-1][j]
        int temp = mat[i][j];
        mat[i][j] = mat[i][n - j - 1];
        mat[i][n - j - 1] = temp;
      }
    }
  }
Output

Matrix Rotation with Transpose

<= Original Matrix  =>

[    1        2        3    ]

[    4        5        6    ]

[    7        8        9    ]



<= After Transpose =>

[    1        4        7    ]

[    2        5        8    ]

[    3        6        9    ]



<= After Rotation =>

[    7        4        1    ]

[    8        5        2    ]

[    9        6        3    ]

Matrix Rotation in Single pass

MatrixRotation.java
The following code will rotate the matrix in a single pass.
public void rotate(int[][] matrix) {
    int n = matrix.length;
    for (int i = 0; i < (n + 1) / 2; i++) {
      for (int j = 0; j < n / 2; j++) {
        int temp = matrix[n - 1 - j][i];
        matrix[n - 1 - j][i] = matrix[n - 1 - i][n - j - 1];
        matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 - i];
        matrix[j][n - 1 - i] = matrix[i][j];
        matrix[i][j] = temp;
      }
    }
  }
Output

Matrix Rotation with single pass

<= Original Matrix  =>

[    1        2        3    ]

[    4        5        6    ]

[    7        8        9    ]



<= After Rotation =>

[    7        4        1    ]

[    8        5        2    ]

[    9        6        3    ]