Search code examples
javamatrixmatrix-inverserotational-matrices

Rotate matrix confusion in Java


public int[][] Solution(int[][] matrix, int flag) {
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0)  return matrix;
    //int m = matrix.length, n = matrix[0].length;
    int[][] rvalue;
    rvalue = transpose(matrix);
    flip(rvalue, flag);
    return rvalue;
}
// transporse the matrix
private int[][] transpose(int[][] matrix) {
    int m = matrix.length, n = matrix[0].length;
    int[][] rvalue = new int[n][m];
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            rvalue[i][j] = matrix[j][i];
    return rvalue;
}
// clockwise rotate the matrix
private void flip(int[][] matrix, int flag) {
    int m = matrix.length, n = matrix[0].length;
    if (flag == 1) {    
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n / 2; j++) {
                matrix[i][j] ^= matrix[i][n-j-1]; // line 1
                matrix[i][n-j-1] ^= matrix[i][j]; // line 2
                matrix[i][j] ^= matrix[i][n-j-1]; // line 3
            }
    }
}

Above is the code for rotating the matrix (first transporse, then rotate). But I cannot understand the code for line 1,2 and 3, I replaced these three lines with my own following code and it works well.

int temp=matrix[i][j];
matrix[i][j]=matrix[i][matrix[0].length-j-1];
matrix[i][matrix[0].length-j-1]=temp;

Can someone explain what the original three lines doing?


Solution

  • The 3 lines are using the xor operator to exchange values. I would never use it unless you really are hard pressed for memory because, as you obviously noticed, it's very hard to understand.

    Here's a link to some info on the algorithm it's using to exchange the values