c++ solution


  • 0
    H

    Figure out how the value changes: from (i, j) to (j, n - i).

    class Solution {
    public:
        void rotate(vector<vector<int>>& matrix) {
            int N = matrix.size() - 1, M = matrix.size()/2;
           for(int k = 0; k< M; ++k){
                for(int j = k; j < N - k; ++j){
                    doRotate(matrix, k, j);
                }
            }
        }
        ///clockwise value flow: (i, j) -> (j, n-i)
        void doRotate(vector<vector<int>>& matrix, int i, int j){
    
           int i0 = i, j0 = j, n = matrix.size()-1;
           
           swap(i, j); 
           j = n - j;
           
           swap(matrix[i][j], matrix[i0][j0]);
           
           swap(i, j); 
           j = n - j;
           swap(matrix[i][j], matrix[i0][j0]);
           
           swap(i, j); 
           j = n - j;
           swap(matrix[i][j], matrix[i0][j0]);
        }
        
        void swap(int & a, int & b){
            int t = a;
            a = b;
            b = t;
        }
    };
    

Log in to reply
 

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