Rotate matrix 90 degrees clockwise Please suggest improvements and a possible better way of doing it in place.

public static void main(String[] args) {
    int[][] mat = { { 1, 2 }, { 3, 4 } };
    rotate(mat);
}

public static void rotate(int[][] matrix) {
    if (matrix == null) {
        return;
    }
    int n = matrix.length - 1;
    int temp = 0;
    int[][] mat2 = new int[n + 1][n + 1];
    mat2 = matrix;
    for (int row = 0; row &lt;= n; row++) {
        for (int col = 0; col &lt;= n; col++) {
            // mat2[n-col][row] = matrix[row][col];
            temp = matrix[col][n - row];
            matrix[col][n - row] = matrix[row][col];
            matrix[row][col] = temp;
        }
    }
    for (int i = 0; i &lt;= n; i++) {
        for (int j = 0; j &lt;= n; j++) {
            matrix[i][j] = mat2[i][j];
        }
    }
}
Yes there is a better way to do it. It makes the computation really simple and elegant.

If you take the transpose of the matrix and then rotate the matrix row-wise along the mid row, you can get the same result as rotating the matrix by 90 degrees counter clock-wise.

For example:

[1 2 3] 
[4 5 6] 
[7 8 9]


Step 1: take its transpose:

[1 4 7]
[2 5 8]
[3 6 9]


Step 2: rotate the matrix across mid row:

[3 6 9]
[2 5 8]
[1 4 7]


This is exactly what you get when you rotate the matrix by 90 degrees left.

Here is the code:

public static void rotateMatrix(int[][] matrix){
    if(matrix == null)
        return;
    if(matrix.length != matrix[0].length)//INVALID INPUT
        return;
    getTranspose(matrix);
    rorateAlongMidRow(matrix);      
}

private static void getTranspose(int[][] matrix) {
    for(int i = 0; i &lt; matrix.length; i++){
        for(int j = i+1; j &lt; matrix.length ; j++){
            int temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }
}

private static void rorateAlongMidRow(int[][] matrix) {
    int len = matrix.length ;
    for(int i = 0; i &lt; len/2; i++){
        for(int j = 0;j &lt; len; j++){
            int temp = matrix[i][j];
            matrix[i][j] = matrix[len-1 -i][j];
            matrix[len -1 -i][j] = temp;
        }
    }
}


Edit: As suggested in the comment, for making it rotate clock-wise, just change the function getTranspose() to rotateAlongDiagonal() in rotateMatrix() function.

private static void rotateAlongDiagonal(int[][] matrix) {
    int len = matrix.length;
    for(int i = 0; i &lt; len; i++){
        for(int j = 0; j &lt; len - 1 - i ; j++){
            int temp = matrix[i][j];
            matrix[i][j] = matrix[len -1 - j][len-1-i];
            matrix[len -1 - j][len-1-i] = temp;
        }
    }
}