c++ recursion method, O(1) space


  • 0
    X
    void rotate(vector<vector<int>>& matrix) {
            helper(matrix, 0, matrix.size() - 1);
        }
    void helper(vector<vector<int>>& matrix, int start, int end){
            if (start >= end) return;
            //rotate the outer shell of matrix
            for(int i = 0; i < end-start; i++){
                int tmp = matrix[start][start+i];
                matrix[start][start+i] = matrix[end-i][start];
                matrix[end-i][start] = matrix[end][end-i];
                matrix[end][end-i] = matrix[start+i][end];
                matrix[start+i][end] = tmp;
            }
            
            helper(matrix, start+1, end-1);
        }
    

Log in to reply
 

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