6 lines of code and with O(1) space in c++

  • 33

    First we transpose the matrix and then reverse every row:

    void rotate(vector<vector<int>>& m) {
            int n = m.size();
            for(int i=0; i<n; i++)
                for(int j=0; j<i; j++)
                    swap(m[i][j], m[j][i]);
            for(int i=0; i<n; i++)
                reverse(m[i].begin(), m[i].end());

Log in to reply

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