C++ 8-line in-place with clear comments

  • 1
        void rotate(vector<vector<int>>& matrix) {
            // rotate each square with thickness of one number. [i, i] is left-up corner of current square
            for (int i=0; i<matrix.size()/2; i++) { 
                int len=matrix.size() - 2*i; // side length of current square
                for (int j=0; j<len-1; j++) { // for each number on upper side of current square
                    // rotate the four numbers on four sides of current square
                    int t = matrix[i][i+j];
                    matrix[i][i+j] = matrix[i+len-1-j][i];
                    matrix[i+len-1-j][i] = matrix[i+len-1][i+len-1-j];
                    matrix[i+len-1][i+len-1-j] = matrix[i+j][i+len-1];
                    matrix[i+j][i+len-1] = t;

Log in to reply

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