Java two flips in-place solution with explanation


  • 0

    First flip about horizontal axis, e.g.
    12
    34
    becomes
    34
    12
    and note that we only need to swap row references.

    Second flip about diagonal axis, e.g.
    34
    12
    becomes
    31
    42
    and note that the diagonal axis 23 should not be touched, only 14 need to be swapped.

        public void rotate(int[][] matrix) {
            int l = matrix.length;
            for (int r = 0; r < l / 2; r++)
                swap(matrix, r, l - r - 1); 
            for (int r = 0; r < l - 1; r++)
                for (int c = r + 1; c < l; c++)
                    swap(matrix, r, c, c, r); 
        }   
    
        static void swap(int[][] matrix, int a, int b) {
            int[] row = matrix[a];
            matrix[a] = matrix[b];
            matrix[b] = row;
        }   
    
        static void swap(int[][] matrix, int a, int b, int c, int d) {
            matrix[a][b] ^= matrix[c][d];
            matrix[c][d] ^= matrix[a][b];
            matrix[a][b] ^= matrix[c][d];
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.