My Concise 4ms C++ Solution ( rotate circle by circle from inside out )


  • 0
    V

    class Solution {

    public:

    void rotate(vector<vector<int>>& matrix) {
        if(matrix.size() < 2){
            return;
        }
        int i = matrix.size()/2 - 1;            // i   : top-left node index of the initial circle 
        int n = 2 + matrix.size()%2;            // n   : edge length of the initial circle
        int tmp;                                // tmp : extra O(1) space
        while(i >= 0){                          // rotate circle by circle from inside out
            for(int k = 0; k < n-1; k++){
                tmp = matrix[i][i+k];
                matrix[i][i+k] = matrix[i+n-1-k][i];
                matrix[i+n-1-k][i] = matrix[i+n-1][i+n-1-k];
                matrix[i+n-1][i+n-1-k] = matrix[i+k][i+n-1];
                matrix[i+k][i+n-1] = tmp;
            }
            n += 2;
            --i;
        }
    }
    

    };


Log in to reply
 

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