C++ 4ms, O(1) space, rotate by squares - from the outermost to the innermost


  • 0
    X
    void rotate(vector<vector<int>>& matrix) {
        // rotate by squares: n - 1 clockwise in the outermost square, n - 3 - the next inner one, etc.
        int inc = matrix.size() - 1;
        int row1 = 0, col1 = 0;
        int row2 = 0, col2 = inc;
        int row3 = inc, col3 = inc;
        int row4 = inc, col4 = 0;
        while(inc > 0)
        {
            for(auto i = 0; i < inc; ++i)
            {
                swap(matrix[row1][col1 + i], matrix[row2 + i][col2]);
                swap(matrix[row1][col1 + i], matrix[row3][col3 - i]);
                swap(matrix[row1][col1 + i], matrix[row4 - i][col4]);
            }
    
            inc -= 2;
            ++row1;
            ++col1;
            ++row2;
            --col2;
            --row3;
            --col3;
            --row4;
            ++col4;
        }
    }

Log in to reply
 

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