My two C++ solutions, 4ms


  • 0
    D

    The ultimate goal we want to achieve is to move [i, j] ->[n-1-j, i]
    First version is to do two flips, first flip around the anti-diagnal line (i.e [i,j]<->[n-1-j, n-1-i]), then we flip the matrix around the horizontal middle line (i.e. [i,j] <-> [n-1-i, j])

    class Solution {
    public:
        void rotate(vector<vector<int>>& matrix) {
            int n = matrix.size(), i,j;
            if(n<=1) return;
            //first flip
            for(i=0; i<n;++i)
                for(j=0;j<n-1-i;++j)
                    swap(matrix[i][j], matrix[n-1-j][n-1-i]);
            // second flip        
            for(i=0; i<n/2;++i)
                for(j=0;j<n;++j)
                    swap(matrix[i][j], matrix[n-1-i][j]);
        }
    };
    

    The second version is to do in-place rotation layer by layer (from outer to inner)

    class Solution {
    public:
        void rotate(vector<vector<int>>& matrix) {
            int m, n, i, j, temp;
            if( (n= matrix.size())<=0 ) return;
            for(i=0; i<n/2; ++i)  // layer by layer rotation
                for(j=i; j<n-1-i; ++j)  // be careful about the starting/ending points of j
                {
                    temp = matrix[i][j];
                    matrix[i][j] = matrix[n-1-j][i];
                    matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
                    matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
                    matrix[j][n-1-i] = temp;
                }
        }
    };

Log in to reply
 

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