Share my inplace solution

  • 11
        class Solution {
        //fold for the middle, fold for the diagnal
        void rotate(vector<vector<int> > &matrix) {
            //find middle
            int mid = matrix.size()/2;
            int n = matrix.size();
            //swap, i swap with matrix.size()-1-i
            for(int i = 0; i < mid; i++){
                for(int j = 0; j < n; j++){
                    swap(matrix[i][j], matrix[n-1-i][j]);
            //swap, i,j swap with j,i
            for(int i = 0; i < n; i++){
                for(int j = i; j < n; j++){
                    swap(matrix[i][j], matrix[j][i]);

    Fold matrix once to the middle line. Fold matrix one more time along the diagonal line.

  • 0

    A very smart solution. How did you find it?

Log in to reply

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