Simple C++, recursion, const memory, in place solution


  • 0
    N

    This solution moves one element at a time to the right place. It is about doing multiple swaps to frame the outer ring.

    class Solution {
    public:
    
        void matrixRotate(vector<vector<int>>& matrix, int sr, int er, int sc, int ec) {
            if(sr>=er || sc >= ec) return;
            for(int i=0; i<ec-sc; i++) {
                swap(matrix[sr][sc+i],matrix[sr+i][ec]);
                swap(matrix[sr][sc+i],matrix[er][ec-i]);
                swap(matrix[sr][sc+i],matrix[er-i][sc]);
            }
            matrixRotate(matrix,sr+1,er-1,sc+1,ec-1);
            return;
        }
        
        void rotate(vector<vector<int>>& matrix) {
            int rows = matrix.size();
            if(!rows) return;
            int cols = matrix[0].size();
            matrixRotate(matrix,0,rows-1,0,cols-1);
        }
    };

Log in to reply
 

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