Easy c++ in place solution less than 20 lines


  • 0
    I
    class Solution {
    public:
        void rotate(vector<vector<int>>& matrix) {
            int n = matrix.size();
            for(int i = 0; i <= (n - 1) / 2; i++) {
                for(int j = 0; j <= n / 2 - 1; j++ ) { // when n is odd, the (0 -> n /2 , n / 2) will rotate twice, so we make j <= n / 2 - 1
                    int ii = i, jj = j;
                    int tmp = matrix[i][j];
                    for(int k = 0; k < 3; k++) {
                        matrix[ii][jj] = matrix[n-1-jj][ii];
                        int t = ii;
                        ii = n - 1 - jj;
                        jj = t;
                    }
                    matrix[ii][jj] = tmp;
                }
            }
        }
    };
    

Log in to reply
 

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