Joey LIU | NANTSOU


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * The key point is that rotating the matrix by 90 degrees clockwise equals to doing transpose and flip.
 *
 */
class Solution {
    public void rotate(int[][] matrix) {
        transpose(matrix);
        flip(matrix);
    }
    
    private void transpose(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < i; j++) {
                matrix[i][j] = matrix[i][j]^matrix[j][i];
                matrix[j][i] = matrix[i][j]^matrix[j][i];
                matrix[i][j] = matrix[i][j]^matrix[j][i];
            }
        }
    }
    
    private void flip(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            int l = 0, r = matrix[i].length - 1;
            while (l < r) {
                matrix[i][l] = matrix[i][l]^matrix[i][r];
                matrix[i][r] = matrix[i][l]^matrix[i][r];
                matrix[i][l] = matrix[i][l]^matrix[i][r];
                l++;
                r--;
            }
        }
    }
}