Share my 4ms swap-in-place C++ solution


  • 0
    R
    class Solution {
    public:
        void rotate(vector<vector<int>>& matrix) {
            int rows = matrix.size();
            int cols = matrix[0].size();
            if(rows!=cols) return;
        
            // diagonal-flip
            for (int r = 0; r < rows/2; ++r){
                for (int c = r; c < cols-r-1; ++c){
                    // swap up bound and right bound
                    swap(matrix, r, c, rows-c-1, cols-r-1);
                    // swap left bound and down bound
                    swap(matrix, c+1, r, rows-r-1, cols-c-2);
                }
            }
        
            // flip horizontal
            for(int r = 0; r < rows/2; ++r){
                for (int c = 0; c < cols; ++c){
                    // swap up and down
                    swap(matrix, r, c, rows-r-1, c);
                }
            }
        }
    
        void swap(vector<vector<int>>& matrix, int i1, int j1, int i2, int j2){
            int t = matrix[i1][j1];
            matrix[i1][j1] = matrix[i2][j2];
            matrix[i2][j2] = t;
        }
    };

Log in to reply
 

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