C solution simple with explanation O(1) space


  • 0
    A

    You start from the corner and you move the

    1. upper left corner to the upper right corner
    2. upper right corner to the bottom right corner
    3. bottom right corner to the bottom left corner
    4. bottom left corner to upper left corner.

    Then you move to the next column and repeat but with the adjustments.

    After that is done you move inward diagonally and repeat. This took me a good 1.5 hours to do.

    void rotate(int** matrix, int matrixRowSize, int matrixColSize) {
        if (matrixRowSize < 2)
           return;
    
        int n = matrixRowSize;
        int i = 0;
        
        while (n > 1) {
            
            for (int col = 0; col < n - 1; col++) {
                int temp = matrix[i][i + col];
                
                //upper right
                int tr = matrix[i + col][i + n - 1];      
                matrix[i + col][i + n - 1] = temp;
                temp = tr;
    
                //bottom right
                tr = matrix[i + n - 1][i + n - 1 - col];      
                matrix[i + n - 1][i + n - 1 - col] = temp;
                temp = tr;
                
                //bottom left
                tr = matrix[i + n - 1 - col][i];  
                matrix[i + n - 1 - col][i] = temp;
    
                //return back
                matrix[i][i + col] = tr;
          }
    
                ++i;
                //cut off the ends
                n = n - 2;
        }    
    }
    

Log in to reply
 

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